我有以下兩個嵌套列表List 1: [["Bob", "Davon", "Alex"],["Dylan","Rose", "Hard"]] List 2: [["Red", "Black"] , ["Blue", "Green"], ["Yellow", "Pink"]]并希望一起顯示嵌套中每個列表的第一個單詞,第二個等等。這樣結(jié)果將是:['Bob and Dylan', 'Davon and Rose', 'Alex and Hard'] --> for the first list['Red and Blue and Yellow, 'Black and Green and Pink'] --> for the second list所以我可以用下面的代碼得到第一個結(jié)果name_list = [["Bob", "Davon", "Alex"],["Dylan","Rose", "Hard"]] def addition(name_list): new_list = [] for i in range(len(name_list)): for j in range(len(name_list[i])): new_list.append(name_list[i][j] + " and " + name_list[i+1][j]) return new_list addition (name_list)但第二個清單:[["Red", "Black"] , ["Blue", "Green"], ["Yellow", "Pink"]]沒有提供正確的結(jié)果。
2 回答

白板的微信
TA貢獻1883條經(jīng)驗 獲得超3個贊
names_list = ["{} and {}".format(*t) for t in zip(*name_list)]
colors_list = ["{} and {}".format(*t) for t in zip(*color_list)]
這可能不適用于python2.7,無論如何你最好升級到python3,因為python2即將結(jié)束

牧羊人nacy
TA貢獻1862條經(jīng)驗 獲得超7個贊
[' and '.join(x) for x in zip(*name_list)]
[' and '.join(x) for x in zip(*color_list)]
str.join()將在任何大小的列表上工作,將字符串放置在每個項目之間。
添加回答
舉報
0/150
提交
取消