假设我有这个列表:
[1,2,3,4]
我想要:
[1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4]
这样做的最佳方法是什么?
我目前的方法是创建一个新列表:
x = [1,2,3,4]
y = [[n]*4 for n in x]
这给出:
[[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]
哪个看起来很近但没有雪茄...有人可以帮忙吗?
最佳答案
>>> x = [1,2,3,4]
>>> [n for n in x for _ in range(4)]
[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]
itertools.repeat
在语义上确实更清晰,谢谢,Steven:
from itertools import repeat
[repeated for value in x for repeated in repeat(value, 4)]
关于python - 如何增加和填充 python 列表的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15412906/