如何解决Python:将列表与列表列表组合
首先,我给出了以年+月为字符串的列表:
li1 = ["2018-01-","2018-02-","2018-03-"]
li2 = [["1","2","3"],["1","2"],["5","9"]]
我想获得以下结果:
combined_list = ["2018-01-1","2018-01-2","2018-01-3","2018-02-1","2018-02-2","2018-03-5","2018-03-9"]
到目前为止我尝试过的事情:
datum = []
count = -1
for y in l1:
for d in li2:
count += 1
name = y + d[count]
datum.append(name)
出现以下错误:“ IndexError:列表索引超出范围”。 问题:
解决方法
结合使用zip
和列表理解
例如:
li1 = ["2018-01-","2018-02-","2018-03-"]
li2 = [["1","2","3"],["1","2"],["5","9"]]
result = [f"{i}{k}" for i,j in zip(li1,li2) for k in j]
print(result)
# --> ['2018-01-1','2018-01-2','2018-01-3','2018-02-1','2018-02-2','2018-03-5','2018-03-9']
,
尝试一下:
li1 = ["2018-01-","9"]]
new_lst = [f"{li1_e}{li2_e2}" for li1_e in li1 for li2_e in li2 for li2_e2 in li2_e]
print(new_lst)
输出:
['2018-01-1','2018-01-1','2018-01-5','2018-01-9','2018-02-3','2018-02-5','2018-02-9','2018-03-1','2018-03-2','2018-03-3','2018-03-9']
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。