交替组合两个列表

问题描述 投票:0回答:2

我正在做一个简单的列表理解:以替代顺序组合两个列表并创建另一个列表。

big_list = [i,j for i,j in zip(['2022-01-01','2022-02-01'],['2022-01-31','2022-02-28'])]

预期输出:

['2022-01-01','2022-01-31','2022-02-01','2022-02-28']

当前输出:

Cell In[35], line 1
    [i,j for i,j in zip(['2022-01-01','2022-02-01'],['2022-01-31','2022-02-28'])]
     ^
SyntaxError: did you forget parentheses around the comprehension target?
python python-3.x list zip list-comprehension
2个回答
1
投票

进行嵌套理解以将项目从压缩元组中拉出:

big_list = [
    i
    for t in zip(
        ['2022-01-01','2022-02-01'],
        ['2022-01-31','2022-02-28']
    ) for i in t
]

0
投票

你可以这样做:

[item for sublist in zip(['2022-01-01','2022-02-01'],['2022-01-31','2022-02-28']) for item in sublist]

#output

['2022-01-01', '2022-01-31', '2022-02-01', '2022-02-28']
© www.soinside.com 2019 - 2024. All rights reserved.