我有以下两个嵌套列表List 1: [["Bob", "Davon", "Alex"],["Dylan","Rose", "Hard"]] List 2: [["Red", "Black"] , ["Blue", "Green"], ["Yellow", "Pink"]]并希望一起显示嵌套中每个列表的第一个单词,第二个等等。这样结果将是:['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所以我可以用下面的代码得到第一个结果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"]]没有提供正确的结果。
2 回答

白板的微信
TA贡献1883条经验 获得超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即将结束

牧羊人nacy
TA贡献1862条经验 获得超7个赞
[' and '.join(x) for x in zip(*name_list)]
[' and '.join(x) for x in zip(*color_list)]
str.join()将在任何大小的列表上工作,将字符串放置在每个项目之间。
添加回答
举报
0/150
提交
取消