likes
comments
collection
share

Hunter狩猎者夹子机器人swap自动交易机器人哈希竞猜农场烤吐司游戏LP流动性节点质押智能合约合

作者站长头像
站长
· 阅读数 315

1、重复元素判定以下方法可以检查给定列表是不是存在重复元素,它会使用 set() 函数来移除所有重复元素。

def all_unique(lst):

return len(lst)== len(set(lst))

x = [1,1,2,2,3,2,3,4,5,6]

y = [1,2,3,4,5]

all_unique(x) # False

all_unique(y) # TrueHunter狩猎者夹子机器人swap自动交易机器人哈希竞猜农场烤吐司游戏LP流动性节点质押智能合约合2、分块给定具体的大小,定义一个函数以按照这个大小切割列表。

from math import ceil

def chunk(lst, size):

return list(

map(lambda x: lst[x size:x size + size],

list(range(0, ceil(len(lst) / size)))))

chunk([1,2,3,4,5],2)

[[1,2],[3,4],5]

3、压缩这个方法可以将布尔型的值去掉,例如(False,None,0,“”),它使用 filter() 函数。

def compact(lst):

return list(filter(bool, lst))

compact([0, 1, False, 2, '', 3, 'a', 's', 34])

[ 1, 2, 3, 'a', 's', 34 ]

4、 使用枚举我们常用 For 循环来遍历某个列表,同样我们也能枚举列表的索引与值。

list = ["a", "b", "c", "d"]

for index, element in enumerate(list):

print("Value", element, "Index ", index, )

('Value', 'a', 'Index ', 0)

('Value', 'b', 'Index ', 1)

('Value', 'c', 'Index ', 2)

('Value', 'd', 'Index ', 3)\

5、解包如下代码段可以将打包好的成对列表解开成两组不同的元组。

array = [['a', 'b'], ['c', 'd'], ['e', 'f']]

transposed = zip(*array)

print(transposed)

[('a', 'c', 'e'), ('b', 'd', 'f')]

6、展开列表该方法将通过递归的方式将列表的嵌套展开为单个列表。

def spread(arg):

ret = []

for i in arg:

if isinstance(i, list):

ret.extend(i)

else:

ret.append(i)

return ret

def deep_flatten(lst):

result = []

result.extend(

spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst))))

return result

deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]

7、 列表的差该方法将返回第一个列表的元素,其不在第二个列表内。如果同时要反馈第二个列表独有的元素,还需要加一句 set_b.difference(set_a)。

def difference(a, b):

set_a = set(a)

set_b = set(b)

comparison = set_a.difference(set_b)

return list(comparison)

difference([1,2,3], [1,2,4]) # [3]

8、 执行时间如下代码块可以用来计算执行特定代码所花费的时间。

import time

start_time = time.time()

a = 1

b = 2

c = a + b

print(c) #3

end_time = time.time()

total_time = end_time - start_time

print("Time: ", total_time)

('Time: ', 1.1205673217773438e-05)

9、 Shuffle该算法会打乱列表元素的顺序,它主要会通过 Fisher-Yates 算法对新列表进行排序:

from copy import deepcopy

from random import randint

def shuffle(lst):

temp_lst = deepcopy(lst)

m = len(temp_lst)

while (m):

m -= 1

i = randint(0, m)

temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m]

return temp_lst

foo = [1,2,3]

shuffle(foo) # [2,3,1] , foo = [1,2,3]

10、 交换值不需要额外的操作就能交换两个变量的值。

def swap(a, b):

return b, a

a, b = -1, 14

swap(a, b) # (14, -1)

spread([1,2,3,[4,5,6],[7],8,9])

[1,2,3,4,5,6,7,8,9]