gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:01:35 25 4
gpt4 key购买 nike

我有以下两个嵌套列表

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

关于python - 带有 for 循环的嵌套字符串列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58209181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com