如果您希望能够处理任何长度的列表(不仅可以被 4 整除,而且不仅仅是两个列表具有相同大小)和任意数量的列表...
任何列表长度
这可以处理任何列表长度,包括两个列表的长度完全不同的地方:
result = []
it1, it2 = iter(List1), iter(List2)
while chunk := list(islice(it1, 4)) + list(islice(it2, 4)):
result += chunk
轻微替代:
result = []
it1, it2 = iter(List1), iter(List2)
while chunk := list(chain(islice(it1, 4), islice(it2, 4))):
result += chunk
演示:
>>> from itertools import islice
>>> List1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> List2 = ['a', 'b', 'c', 'd', 'e']
>>> k = 4
>>> result = []
>>> it1, it2 = iter(List1), iter(List2)
>>> while chunk := list(islice(it1, k)) + list(islice(it2, k)):
result += chunk
>>> result
[1, 2, 3, 4, 'a', 'b', 'c', 'd', 5, 6, 7, 8, 'e', 9, 10, 11, 12, 13, 14]
任意数量的列表(任意长度)
result = []
iters = deque(map(iter, Lists))
while iters:
it = iters.popleft()
if chunk := list(islice(it, 4)):
result += chunk
iters.append(it)
演示(为清晰起见格式化输出):
>>> from itertools import islice
>>> from collections import deque
>>> Lists = [
[1.1, 1.1, 1.1, 1.1, 1.2, 1.2, 1.2, 1.2],
[2.1, 2.1, 2.1, 2.1, 2.2, 2.2, 2.2, 2.2, 2.3],
[3.1, 3.1, 3.1, 3.1, 3.2, 3.2, 3.2, 3.2, 3.3, 3.4]
]
>>> k = 4
>>> result = []
>>> iters = deque(map(iter, Lists))
>>> while iters:
it = iters.popleft()
if chunk := list(islice(it, 4)):
result += chunk
iters.append(it)
>>> result
[1.1, 1.1, 1.1, 1.1, 2.1, 2.1, 2.1, 2.1, 3.1, 3.1, 3.1, 3.1,
1.2, 1.2, 1.2, 1.2, 2.2, 2.2, 2.2, 2.2, 3.2, 3.2, 3.2, 3.2,
2.3, 3.3, 3.4]