【386】operator 的 itemgetter 和 slice

itemgetter

用来获取数组中指定索引的元素

from operator import itemgetter
itemgetter(1, 3, 5)('ABCDEFG')

output:
('B', 'D', 'F')

slice

用来为列表切片,也是获取指定索引的元素

a = slice(0,10,2)
b = list(range(10))
b[a]
b[0:10:2]
itemgetter(a)(b)

output:
[0, 2, 4, 6, 8]
[0, 2, 4, 6, 8]
[0, 2, 4, 6, 8]

猜你喜欢

转载自www.cnblogs.com/alex-bn-lee/p/10571087.html