【发布时间】:2022-11-27 00:00:22
【问题描述】:
我正在尝试用该特定列表的索引值替换列表列表中的项目。我可以用 for 循环来做,但我想知道是否有更快的方法来做到这一点。
这样下面的列表
example = [[1,2,3], [4,5,6], [7,8,9]]
变成:
solution = [[0,0,0], [1,1,1], [2,2,2]]
【问题讨论】:
我正在尝试用该特定列表的索引值替换列表列表中的项目。我可以用 for 循环来做,但我想知道是否有更快的方法来做到这一点。
这样下面的列表
example = [[1,2,3], [4,5,6], [7,8,9]]
变成:
solution = [[0,0,0], [1,1,1], [2,2,2]]
【问题讨论】:
列表理解通常比循环更快
这是一个列表理解的解决方案
example = [[1,2,3],[4,5,6],[7,8,9]]
solution = [[x for _ in range(len(example[x]))] for x in range(len(example))]
print(solution)
Output
[[0, 0, 0], [1, 1, 1], [2, 2, 2]]
【讨论】:
enumerate()?您可以使用乘法生成一定长度的列表。
你使用 for 循环的方式应该可行,但如果你想要另一种简短版本的方式,那么你可以这样做,
example = [[1,2,3],[4,5,6],[7,8,9]]
result = [[i, i, i] for i,_ in enumerate(example)]
print(result)
【讨论】:
这是map操作的解决方案:
res = list(map(lambda i : [i] * len(example[i]),
range(len(example))
))
print(res)
它比理解方法更冗长,但来自其他语言我更喜欢它 - 我发现 map 更明确且更容易理解,因为它是由高阶函数的公共组件构建的,而不是拥有自己的组件句法。
【讨论】: