如何以列表格式获得预期的输出

how to get the expected output in list format

下面是 2 个 lst1 和 lst2,预期输出如下所示。

lst1 = ['q','r','s','t','u','v','w','x','y','z']


lst2 =['1','2','3']

预期输出

 [['q','1'], ['r','2'], ['s','3'], ['t','1'],['u','2'],['v','3'],['w','1'],['x','2'],['y','3'], 
['z','1']]"

您可以使用 zip() and itertools.cycle().

from itertools import cycle

lst1 = ['q','r','s','t','u','v','w','x','y','z']
lst2 =['1','2','3']

result = [[letter, number] for letter, number in zip(lst1, cycle(lst2))]
print(result)

预期输出:

[['q', '1'], ['r', '2'], ['s', '3'], ['t', '1'], ['u', '2'], ['v', '3'], ['w', '1'], ['x', '2'], ['y', '3'], ['z', '1']]

另一种解决方案是另外使用 map().

result = list(map(list, zip(lst1, cycle(lst2))))

如果您想使用元组,您可以这样做

from itertools import cycle

lst1 = ['q','r','s','t','u','v','w','x','y','z']
lst2 =['1','2','3']


result = list(zip(lst1, cycle(lst2)))
print(result)

哪个会给你

[('q', '1'), ('r', '2'), ('s', '3'), ('t', '1'), ('u', '2'), ('v', '3'), ('w', '1'), ('x', '2'), ('y', '3'), ('z', '1')]

这是解决此问题的一种非常简单的方法。

lst1 = ['q','r','s','t','u','v','w','x','y','z']
lst2 = ['1','2','3']

new_list = []

for x in range(len(lst1)):
    new_list.append([lst1[x], lst2[x % 3]])

print(new_list) # [['q', '1'], ['r', '2'], ['s', '3'], ['t', '1'], ['u', '2'], ['v', '3'], ['w', '1'], ['x', '2'], ['y', '3'], ['z', '1']]

你也可以在这种情况下使用列表理解,像这样:-

new_list = [[lst1[x], lst2[x % 3]] for x in range(len(lst1))]