提问人:wiseass 提问时间:10/13/2022 更新时间:10/13/2022 访问量:70
for loop/list-comprehensions 应用 zip_longest for list 组合得到 (l1[0]:l2[0]) 而不得到 l1[0]:l2[1])
for loop/list-comprehensions to apply zip_longest for list of lists combinations to get (l1[0]:l2[0]) without getting l1[0]:l2[1])
问:
我一直在努力合并列表列表......测试有关 zip、zip_longest、列表、列表推导、遍历等长列表列表的各种问题的答案,但我无法找到一个可以解决我的问题的方法。我现在被打败了。
这很可能是我缺乏经验的结果,但我已经没有地方可以看了。
我有两个列表列表,内部列表具有不同的长度。
我想zip_longest每个内部列表,结果类型如下: [('1', '1.一种方法'), ('2', '2.方法'), ('描述', '3.描述')等]
下面显示的尝试得到了我喜欢的结果,但代码生成将 list_1[0] 与 list_2[1] 交叉组合。我只想将相同索引(list_1[0] 与 list_2[0])的列表组合在一起,然后是 1:1、2:2。
from itertools import zip_longest
claim_text = [['1. A method', '2. The method', '3. Description'],
['1. A method', '2. The method', '3. The method', '5. The method']];
claim_num = [['1', '2'], ['1', '2', '3']]
combined = []
for i in claim_text:
for x in claim_num:
combined.append(list(itertools.zip_longest(x,i, fillvalue='Description')))
print(combined)
另一种方法:
[(list(itertools.zip_longest(a,b, fillvalue='Description'))) for a in claim_num for b in claim_text]
任何帮助都是值得赞赏的。
答:
1赞
mozway
10/13/2022
#1
你想用第一个文本的第一个数字,用第二个文本的第二个null,等等?zip_longest
然后首先将两个输入的子列表与以下内容组合在一起:zip
[list(zip_longest(a, b, fillvalue='Description'))
for a, b in zip(claim_num, claim_text)]
输出:
[[('1', '1. A method'),
('2', '2. The method'),
('Description', '3. Description')],
[('1', '1. A method'),
('2', '2. The method'),
('3', '3. The method'),
('Description', '5. The method')]]
评论
zip