中风“key = len”是什么意思?

阿列克谢·格拉博

请告诉我 string 'sorted(args, key=len)[0] 是做什么的?

names = ['Bruce', 'Clark', 'Peter'] 
heroes = ['Batman', 'Superman', 'Spiderman']

def shortest_seq(*args):
     return range(len(sorted(args, key=len)[0]))

g = ((names[i], heroes[i]) for i in shortest_seq(names, heroes))
for item in g:
    print(item)
英维·莫

sorted函数采用一个可选参数 ,key该函数用于测量列表元素的大小。因此,在您的情况下,您是按长度对列表集合进行排序。

例子:

L1 = [1, 2, 3, 4]
L2 = sorted(L1, key=lambda x: -x)  # [4, 3, 2, 1]
L3 = sorted(L1, key=lambda x: x % 2)  # [2, 4, 1, 3]

因此,函数

def shortest_seq(*args):
    return range(len(sorted(args, key=len)[0]))

获取任意数量的可迭代对象并返回一个列表(不是真正的范围对象,但足够接近),其中的数字为 0 到 n-1,其中 n 是提供给函数的最短可迭代对象的长度。

编码

g = ((names[i], heroes[i]) for i in shortest_seq(names, heroes))
for item in g:
    print(item)

将执行相同的

for item in zip(names, heroes)
    print item

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章