List python skill
总结了43个列表操作常用到的一些技巧,加快处理与列表相关的问题
文章目录
- List python skill
- 1. all_equal
- 2. all_unique
- 3. bifurcate
- 4. bifurcate_by
- 5. chunk
- 6. compact
- 7. count_by
- 8. count_occurences
- 9. deep_flatten
- 10. difference
- 11.difference_by
- 12.every
- 13.every_nth
- 14.filter_non_unique
- 15.filter_unique
- 16.flatten
- 17.group_by
- 18.has_duplicates
- 19.head
- 20.initial
- 21.initialize_2d_list
- 22.initialize_list_with_range
- 23.initialize_list_with_values
- 24.intersection
- 25.intersection_by
- 26.last
- 27.longest_item
- 28.max_n
- 29.min_n
- 30.none
- 31.offset
- 32.sample
- 33.shuffle
- 34.similarity
- 35.some
- 36.spread
- 37.symmetric_difference
- 38.symmetric_difference_by
- 39.tail
- 40.transpose
- 41.union
- 42.union_by
- 43.unique_elements
- 44.zip
1. all_equal
检查列表里的元素是否都相等
def all_equal(lst):
return lst[1:] == lst[:-1]
# Examples
all_equal([1, 2, 3, 4, 5, 6]) # False
all_equal([1, 1, 1, 1]) # True
2. all_unique
检查列表中的元素是否独一无二
def all_unique(lst):
return len(lst) == len(set(lst))
# Examples
x = [1,2,3,4,5,6]
y = [1,2,2,3,4,5]
all_unique(x) # True
all_unique(y) # False
3. bifurcate
将列表中的值按真假条件分成两个列表
def bifurcate(lst, filter):
return [
[x for i,x in enumerate(lst) if filter[i] == True],
[x for i,x in enumerate(lst) if filter[i] == False]
]
# Example
bifurcate(['beep', 'boop', 'foo', 'bar'], [True, True, False, True])
# [ ['beep', 'boop', 'bar'], ['foo'] ]
4. bifurcate_by
将列表中的值按一个函数条件分为两个列表
def bifurcate_by(lst, fn):
return [
[x for x in lst if fn(x)],
[x for x in lst if not fn(x)] ]
# example
bifurcate_by(['beep', 'boop', 'foo', 'bar'], lambda x: x[0] == 'b')
# [ ['beep', 'boop', 'bar'], ['foo'] ]
5. chunk
将一个列表分成多个指定大小的较小列表。
from math import ceil # math.ceil(x) 返回不小于x的最小整数
def chunk(lst, size):
return list(
map(lambda x: lst[x * size:x * size + size],
list(range(0, ceil(len(lst) / size)))))
# example
chunk([1,2,3,4,5],2) # [[1,2],[3,4],5]
6. compact
去除列表中假的值包括(False
, None
, 0
, and ""
).
def compact(lst):
return list(filter(bool, lst))
# example
compact([0, 1, False, 2, '', 3, 'a', 's', 34])
# [ 1, 2, 3, 'a', 's', 34 ]
7. count_by
根据给定的函数对列表中的元素进行分组,并返回每个组中元素的计数。
def count_by(arr, fn=lambda x: x):
key = {}
for el in map(fn, arr):
key[el] = 1 if el not in key else key[el] + 1
return key
# example
from math import floor
count_by([6.1, 4.2, 6.3], floor) # {6: 2, 4: 1}
count_by(['one', 'two', 'three'], len) # {3: 2, 5: 1}
8. count_occurences
计算一个值在列表中出现的次数。
def count_occurrences(lst, val):
return len([x for x in lst if x == val and type(x) == type(val)])
# example
count_occurrences([1, 1, 2, 1, 2, 3], 1) # 3
9. deep_flatten
将列表中的元素扁平化。
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
# example
deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]
10. difference
返回两个序列中的不同
def difference(a, b):
_b = set(b)
return [item for item in a if item not in _b]
# example
difference([1, 2, 3], [1, 2, 4]) # [3]
11.difference_by
返回两个列表中的元素经过一个函数操作后不同的元素。
def difference_by(a, b, fn):
_b = set(map(fn, b))
return [item for item in a if fn(item) not in _b]
# example
from math import floor
difference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2]
difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x']) # [ { x: 2 } ]
12.every
如果列表里的元素都满足所提供的函数,则返回True
def every(lst, fn=lambda x: x):
return all(map(fn, lst))
# example
every([4, 2, 3], lambda x: x > 1) # True
every([1, 2, 3]) # True
13.every_nth
返回每一个相隔nth的元素
def every_nth(lst, nth):
return lst[nth-1::nth]
# example
every_nth([1, 2, 3, 4, 5, 6], 2) # [ 2, 4, 6 ]
14.filter_non_unique
过滤掉列表中重复元素,返回独一无二的元素
注意跟set的区别
def filter_non_unique(lst):
return [item for item in lst if lst.count(item) == 1]
# example
filter_non_unique([1, 2, 2, 3, 4, 4, 5]) # [1, 3, 5]
15.filter_unique
过滤掉列表中独一无二的元素,返回有重复的元素,但是只返回一个
def filter_unique(lst):
return [x for x in set(item for item in lst if lst.count(item) > 1)]
# example
filter_unique([1, 2, 2, 3, 4, 4, 5]) # [2, 4]
16.flatten
将列表展平一次
def flatten(lst):
return [x for y in lst for x in y]
# example
flatten([[1,2,3,4],[5,6,7,8]]) # [1, 2, 3, 4, 5, 6, 7, 8]
17.group_by
基于一个函数将列表中的元素进行分类
def group_by(lst, fn):
return {key : [el for el in lst if fn(el) == key] for key in map(fn,lst)}
# example
import math
group_by([6.1, 4.2, 6.3], math.floor) # {4: [4.2], 6: [6.1, 6.3]}
group_by(['one', 'two', 'three'], len) # {3: ['one', 'two'], 5: ['three']}
18.has_duplicates
列表中有重复的元素True,否则返回False
def has_duplicates(lst):
return len(lst) != len(set(lst))
# example
x = [1,2,3,4,5,5]
y = [1,2,3,4,5]
has_duplicates(x) # True
has_duplicates(y) # False
19.head
返回列表中的第一个元素
def head(lst):
return lst[0]
# example
head([1, 2, 3]); # 1
20.initial
返回列表中除了最后一个元素的所有元素
def initial(lst):
return lst[0:-1]
# example
initial([1, 2, 3]); # [1,2]
21.initialize_2d_list
返回一个有h个宽度为w的大列表
def initialize_2d_list(w,h, val = None):
return [[val for x in range(w)] for y in range(h)]
# example
initialize_2d_list(2, 2, 0) # [[0,0], [0,0]]
22.initialize_list_with_range
使用range()方法创建列表
def initialize_list_with_range(end, start = 0, step = 1):
return list(range(start, end + 1, step))
# example
initialize_list_with_range(5) # [0, 1, 2, 3, 4, 5]
initialize_list_with_range(7,3) # [3, 4, 5, 6, 7]
initialize_list_with_range(9,0,2) # [0, 2, 4, 6, 8]
23.initialize_list_with_values
创建一个有n个value的列表
def initialize_list_with_values(n, val = 0):
return [val for x in range(n)]
# example
initialize_list_with_values(5, 2) # [2, 2, 2, 2, 2]
24.intersection
返回两个列表中共有的元素
def intersection(a, b):
_a, _b = set(a), set(b)
return list(_a & _b)
#example
intersection([1, 2, 3], [4, 3, 2]) # [2, 3]
25.intersection_by
返回通过一个函数后两个列表共有的元素
def intersection_by(a, b, fn):
_b = set(map(fn, b))
return [item for item in a if fn(item) in _b]
# example
from math import floor
intersection_by([2.1, 1.2], [2.3, 3.4],floor) # [2.1]
26.last
返回一个列表中的最后一个元素
def last(lst):
return lst[-1]
# example
last([1, 2, 3]) # 3
27.longest_item
返回长度最大的一个对象
def longest_item(*args):
return max(args, key = len)
# example
longest_item('this', 'is', 'a', 'testcase') # 'testcase'
longest_item([1, 2, 3], [1, 2], [1, 2, 3, 4, 5]) # [1, 2, 3, 4, 5]
longest_item([1, 2, 3], 'foobar') # 'foobar'
28.max_n
返回n个从大到小的元素
def max_n(lst, n=1):
return sorted(lst, reverse=True)[:n]
# example
max_n([1, 2, 3]) # [3]
max_n([1, 2, 3], 2) # [3,2]
29.min_n
返回n个从小到大的元素
def min_n(lst, n=1):
return sorted(lst, reverse=False)[:n]
# example
min_n([1, 2, 3]) # [1]
min_n([1, 2, 3], 2) # [1,2]
30.none
如果提供的函数有一个是True,那么返回False
def none(lst, fn=lambda x: x):
return all(not fn(x) for x in lst)
# example
none([0, 1, 2, 0], lambda x: x >= 2 ) # False
none([0, 0, 0]) # True
31.offset
移花接木,把前offset个元素放到后面
def offset(lst, offset):
return lst[offset:] + lst[:offset]
# example
offset([1, 2, 3, 4, 5], 2) # [3, 4, 5, 1, 2]
offset([1, 2, 3, 4, 5], -2) # [4, 5, 1, 2, 3]
32.sample
抽样列表中的一个元素
from random import randint
def sample(lst):
return lst[randint(0, len(lst) - 1)]
# example
sample([3, 7, 9, 11]) # 9
33.shuffle
洗牌操作,打乱列表中的元素
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
# example
foo = [1,2,3]
shuffle(foo) # [2,3,1] , foo = [1,2,3]
34.similarity
返回两个列表中共有的元素
def similarity(a, b):
return [item for item in a if item in b]
# example
similarity([1, 2, 3], [1, 2, 4]) # [1, 2]
35.some
如果提供的函数有一个是True,那么返回True
def some(lst, fn=lambda x: x):
return any(map(fn, lst))
# example
some([0, 1, 2, 0], lambda x: x >= 2 ) # True
some([0, 0, 1, 0]) # True
36.spread
通过将其元素散布到新列表中来使列表变平。
def spread(arg):
ret = []
for i in arg:
if isinstance(i, list):
ret.extend(i)
else:
ret.append(i)
return ret
# example
spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]
37.symmetric_difference
返回两个可迭代对象之间的对称差,而不是过滤出重复的值。
def symmetric_difference(a, b):
_a, _b = set(a), set(b)
return [item for item in a if item not in _b] + [item for item in b if item not in _a]
# example
symmetric_difference([1, 2, 3], [1, 2, 4]) # [3, 4]
38.symmetric_difference_by
通过一个函数来判断,返回两个可迭代对象之间的对称差
def symmetric_difference_by(a, b, fn):
_a, _b = set(map(fn, a)), set(map(fn, b))
return [item for item in a if fn(item) not in _b] + [item for item in b if fn(item) not in _a]
# example
from math import floor
symmetric_difference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2, 3.4]
39.tail
列表元素个数大于1,返回除了第一个元素的所有元素,否则返回本身
def tail(lst):
return lst[1:] if len(lst) > 1 else lst
# example
tail([1, 2, 3]); # [2,3]
tail([1]); # [1]
40.transpose
返回二维列表的转置。
def transpose(lst):
return list(zip(*lst))
# example
transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
# [(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)]
41.union
返回所有没有重复的元素
def union(a,b):
return list(set(a + b))
# example
union([1, 2, 3], [4, 3, 2]) # [1,2,3,4]
42.union_by
将提供的函数应用于两个列表中的每个元素之后,一次返回两个列表中任何一个列表中存在的每个元素。
def union_by(a,b,fn):
_a = set(map(fn, a))
return list(set(a + [item for item in b if fn(item) not in _a]))
# example
from math import floor
union_by([2.1], [1.2, 2.3], floor) # [2.1, 1.2]
43.unique_elements
返回的列表中的元素是独一无二的
def unique_elements(li):
return list(set(li))
# example
unique_elements([1, 2, 2, 3, 4, 3]) # [1, 2, 3, 4]
44.zip
创建元素列表,并根据原始列表中的位置进行分组。
def zip(*args, fillvalue=None):
max_length = max([len(lst) for lst in args])
result = []
for i in range(max_length):
result.append([
args[k][i] if i < len(args[k]) else fillvalue for k in range(len(args))
])
return result
# example
zip(['a', 'b'], [1, 2], [True, False]) # [['a', 1, True], ['b', 2, False]]
zip(['a'], [1, 2], [True, False]) # [['a', 1, True], [None, 2, False]]
zip(['a'], [1, 2], [True, False], fill_value = '_') # [['a', 1, True], ['_', 2, False]]