Skip to main content
 首页 » 编程设计

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

2024年11月01日21insus

我有以下两个嵌套列表

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

请您参考如下方法:

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 即将结束