Python 如何在另一个列表内容中重复一个列表的元素,直到第二个列表的长度满足?
Python How to repeat a list's elements in another list content until the length of the second list fulfilled?
如何在另一个列表内容中重复一个列表的元素,直到第二个列表的长度满足?
例如:
LA = [0,1,2]
LB = [(0,0),(1,0),(2,0),(3,0),(4,0),(5,0),(6,0)]
the end result should be:
LC = [(0,0,0),(1,0,1),(2,0,2),(3,0,0),(4,0,1),(5,0,2),(6,0,0)]
希望能一行完成
像这样尝试 enumerate()
以及列表理解 -
[elem + (LA[i % len(LA)],) for i, elem in enumerate(LB)]
您可以使用 itertools.cycle
:
from itertools import cycle
LA = [0,1,2]
LB = [(0,0),(1,0),(2,0),(3,0),(4,0),(5,0),(6,0)]
LC = [(i, j, k) for (i, j), k in zip(LB, cycle(LA))]
print LC
# [(0, 0, 0), (1, 0, 1), (2, 0, 2), (3, 0, 0), (4, 0, 1), (5, 0, 2), (6, 0, 0)]
这是可行的,因为 zip
会生成项目,直到其中一个可迭代对象耗尽...但是 cycle
对象是 ineexhaustible,所以我们将保留 LA
的填充项目,直到 LB
用完。
#use list comprehension and get the element from LA by using the index from LB %3.
[v+(LA[k%3],) for k,v in enumerate(LB)]
Out[718]: [[0, 0, 0], [1, 0, 1], [2, 0, 2], [3, 0, 0], [4, 0, 1], [5, 0, 2], [6, 0, 0]]
这里有一个更 "explicit" 的版本,适用于任何长度的 LA。
LA = [0,1,2]
LB = [(0,0),(1,0),(2,0),(3,0),(4,0),(5,0),(6,0)]
i = 0
LC = []
for x,y in LB:
try:
z = LA[i]
except IndexError:
i = 0
z = LA[i]
LC.append((x,y,z))
i += 1
print LC
[(0, 0, 0), (1, 0, 1), (2, 0, 2), (3, 0, 0), (4, 0, 1), (5, 0, 2), (6, 0, 0)]
如何在另一个列表内容中重复一个列表的元素,直到第二个列表的长度满足? 例如:
LA = [0,1,2]
LB = [(0,0),(1,0),(2,0),(3,0),(4,0),(5,0),(6,0)]
the end result should be:
LC = [(0,0,0),(1,0,1),(2,0,2),(3,0,0),(4,0,1),(5,0,2),(6,0,0)]
希望能一行完成
像这样尝试 enumerate()
以及列表理解 -
[elem + (LA[i % len(LA)],) for i, elem in enumerate(LB)]
您可以使用 itertools.cycle
:
from itertools import cycle
LA = [0,1,2]
LB = [(0,0),(1,0),(2,0),(3,0),(4,0),(5,0),(6,0)]
LC = [(i, j, k) for (i, j), k in zip(LB, cycle(LA))]
print LC
# [(0, 0, 0), (1, 0, 1), (2, 0, 2), (3, 0, 0), (4, 0, 1), (5, 0, 2), (6, 0, 0)]
这是可行的,因为 zip
会生成项目,直到其中一个可迭代对象耗尽...但是 cycle
对象是 ineexhaustible,所以我们将保留 LA
的填充项目,直到 LB
用完。
#use list comprehension and get the element from LA by using the index from LB %3.
[v+(LA[k%3],) for k,v in enumerate(LB)]
Out[718]: [[0, 0, 0], [1, 0, 1], [2, 0, 2], [3, 0, 0], [4, 0, 1], [5, 0, 2], [6, 0, 0]]
这里有一个更 "explicit" 的版本,适用于任何长度的 LA。
LA = [0,1,2]
LB = [(0,0),(1,0),(2,0),(3,0),(4,0),(5,0),(6,0)]
i = 0
LC = []
for x,y in LB:
try:
z = LA[i]
except IndexError:
i = 0
z = LA[i]
LC.append((x,y,z))
i += 1
print LC
[(0, 0, 0), (1, 0, 1), (2, 0, 2), (3, 0, 0), (4, 0, 1), (5, 0, 2), (6, 0, 0)]