猿问

带有 for 循环的嵌套字符串列表

我有以下两个嵌套列表


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"]]没有提供正确的结果。


烙印99
浏览 122回答 2
2回答

白板的微信

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

[' and '.join(x) for x in zip(*name_list)][' and '.join(x) for x in zip(*color_list)]str.join()将在任何大小的列表上工作,将字符串放置在每个项目之间。
随时随地看视频慕课网APP

相关分类

Python
我要回答