遍历不同的列表

Iterate over different lists

提问人:Vitaliy 提问时间:10/19/2023 最后编辑:Goku - stands with PalestineVitaliy 更新时间:10/19/2023 访问量:80

问:

我正在尝试在 python 中迭代 2 个不同的列表,在此迭代之后,我想获得新列表,其中将包含新数据。

我有一个代码:

import itertools
current_week = [42,43,44,45,46]
late_pcs = [10,27]
late_week = [45,46]

late_list = []
for week, pcs in itertools.zip_longest(current_week, late_pcs):
    if week not in late_week:
        late_list.extend([0])
    else:
        late_list.extend([pcs])

我需要比较 2 个列表。如果列表“current_week”中的数字在“late_week”中,我需要从列表“late_pcs”中获取数字。

我们取数字 42 并开始检查这个数字是否在“late_week”中。如果是 False - 我们在“late_list”中添加 0,依此类推。如果是真的 - 我们从“late_pcs”中添加数字。

因此,我需要获得这样的新列表:

late_list = [0, 0, 0, 10, 27]

但是我得到:

[0, 0, 0, None, None]

我知道我可以将 fillvalue 用于zip_longest,但我认为它以这种方式对我们没有用。 也许我选择了错误的方式来获得正确的结果。

python-3.x for循环 python-itertools

评论

1赞 blhsing 10/19/2023
如果输出是什么?late_week = [45, 43]
0赞 Vitaliy 10/19/2023
实际上late_week = [45, 46]。或者这个列表应该包括什么?
0赞 Homer512 10/19/2023
你是故意避开字典吗?
0赞 blhsing 10/19/2023
我想问的是,中的数字是根据匹配数字的位置来获取的,还是仅仅基于列表顺序?late_pcslate_week

答:

1赞 Hazwick 10/19/2023 #1

这是一个无需导入的解决方案:itertools

current_week = [42,43,44,45,46]
late_pcs = [10,27]
late_week = [45,46]

late_list = []
for week in current_week:
    if week in late_week:
        late_list.append(late_pcs.pop(0))
    else:
        late_list.append(0)

print(late_list)
1赞 Goku - stands with Palestine 10/19/2023 #2

您可以保留一个计数器来保留跟踪。您不需要使用:zip_lingest()

每次从 追加元素时,都会递增计数器late_pcsc

current_week = [42,43,44,45,46]
late_pcs = [10,27]
late_week = [45,46]
late_list = []
c = 0                       # counter variable
for week in current_week:
    if week not in late_week:
        late_list.append(0)
    else:
        if c<len(late_pcs):    # if condition to make sure index dont overlow
            late_list.append(late_pcs[c])
            c+=1

print(late_list)
[0, 0, 0, 10, 27]

评论

0赞 blhsing 10/19/2023
if late_pcs[c]: # if condition to check whether the index c exists or not这不是检查索引是否存在的方式。
0赞 Goku - stands with Palestine 10/19/2023
@blhsing谢谢..你是对的!我已经编辑过了。请看。
1赞 John La Rooy 10/19/2023 #3

这是一个很好的使用场所。iter

使用代替的优点是原始列表保持不变。还会导致列表中每个剩余的项目都会在每次弹出时移动。当您使用长列表时,这可能会导致性能问题。iterpoppop(0)pop(0)

result = []
fill_value = iter(late_pcs)
for week in current_week:
    if week in late_week:
        result.append(next(fill_value))
    else:
        result.append(0)
print(result)

你可以用三元if/else来简化一点

result = []
fill_value = iter(late_pcs)
for week in current_week:
    result.append(next(fill_value) if week in late_week else 0)
print(result)

甚至把它写成一个列表推导

fill_value = iter(late_pcs)
result = [next(fill_value) if week in late_week else 0 for week in current_week]
print(result)