我正在嘗試在 python 3 中組合 n 個這樣的數(shù)組:輸入示例:l1 =["a", "b", "c"]l2 = [1, 2, 3]l3 = ["!", "@", "#"]輸出示例:[['a', 1, '!'], ['b', 2, '@'], ['c', 3, '#']]這是我寫的適用于三個給定輸入的內(nèi)容,但是我需要它適用于 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貢獻(xiàn)1790條經(jīng)驗(yàn) 獲得超9個贊
您可以使用 zip() 來實(shí)現(xiàn):
l1 =["a", "b", "c"]
l2 = [1, 2, 3]
l3 = ["!", "@", "#"]
print(*zip(l1,l2,l3))
# ('a', 1, '!') ('b', 2, '@') ('c', 3, '#')
如果您確實(shí)需要列表列表:
print([list(i) for i in zip(l1,l2,l3)])
# [['a', 1, '!'], ['b', 2, '@'], ['c', 3, '#']]
添加回答
舉報
0/150
提交
取消