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

2024-10-02 04:29:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下两个嵌套列表

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


Tags: andname列表forgreenblueredlist
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已经到了生命的尽头

[' and '.join(x) for x in zip(*name_list)]
[' and '.join(x) for x in zip(*color_list)]

str.join()将处理任意大小的列表,将字符串放在每个项之间

相关问题 更多 >

    热门问题