为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

烙印99 2022-06-14 10:52:53
我有以下两个嵌套列表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即将结束


查看完整回答
反对 回复 2022-06-14
?
牧羊人nacy

TA贡献1862条经验 获得超7个赞

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

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

str.join()将在任何大小的列表上工作,将字符串放置在每个项目之间。


查看完整回答
反对 回复 2022-06-14
  • 2 回答
  • 0 关注
  • 109 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号