我正在尝试在 python 3 中组合 n 个这样的数组:输入示例:l1 =["a", "b", "c"]l2 = [1, 2, 3]l3 = ["!", "@", "#"]输出示例:[['a', 1, '!'], ['b', 2, '@'], ['c', 3, '#']]这是我写的适用于三个给定输入的内容,但是我需要它适用于 n 个列表:def assemble_three_lists(list1, list2, list3):combined_list = []list1_length = len(list1)list2_length = len(list2)list3_length = len(list3)if list1_length != list2_length and list1_length != list3_length: raise Exception("Some elements have been lost, critical error.")else: i = 0 while i < list1_length: combined_list.insert(i, [list1[i], list2[i], list3[i]]) i += 1return combined_list我尝试过这样写:def assemble_lists(list_of_lists):return [list[::] for list in list_of_lists]但我的输出是:[['a', 'b', 'c']], [[1, 2, 3]], [['!', '@', '#']]
1 回答
富国沪深
TA贡献1790条经验 获得超9个赞
您可以使用 zip() 来实现:
l1 =["a", "b", "c"]
l2 = [1, 2, 3]
l3 = ["!", "@", "#"]
print(*zip(l1,l2,l3))
# ('a', 1, '!') ('b', 2, '@') ('c', 3, '#')
如果您确实需要列表列表:
print([list(i) for i in zip(l1,l2,l3)])
# [['a', 1, '!'], ['b', 2, '@'], ['c', 3, '#']]
添加回答
举报
0/150
提交
取消