python - 如何根据列表中的元素数量停止迭代?

标签 python list

我有一个项目,我必须在 on_time 中获取元素的后续元素。

例如:

j_set = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
s_follow_int = [[2, 3], 4, [5, 6], [6, 8], [7, 8], 9, 8, 10, 10, 11]
on_time = [4, 5]

我的代码是这样的:

# element in on_time except 1, get follow_finish_act
follow_finish_act = []

for a, d in zip(j_set, s_follow_int):
    if a in on_time and a != 1:
        if len(on_time) > 1:
            follow_finish_act.append(d)
        else:
            follow_finish_act = d

我得到的输出:

follow_finish_act =  [[6, 8], [7, 8]]

预期输出:

follow_finish_act = [6, 7, 8]

当 on_time 的长度超过 1 时,我遇到了麻烦。我认为问题在于将不规则列表(可以嵌套和整数)展平而没有重复。因为,我无法获得预期的输出。

如有任何帮助/建议,我们将不胜感激!谢谢!

编辑:我用来尝试扁平化 follow_finish_act 输出的代码

def flatten(lss):
    for item in lss:
        try:
            yield from flatten(item)
        except TypeError:
            yield item

最佳答案

您可以通过使用 set 而不是 list 来避免重复

j_set = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
s_follow_int = [[2, 3], 4, [5, 6], [6, 8], [7, 8], 9, 8, 10, 10, 11]
on_time = [4, 5]

follow_finish_act = set()

for a, d in zip(j_set, s_follow_int):
    if a in on_time and a != 1:
        if len(on_time) > 1:
            follow_finish_act.update(d)
        else:
            follow_finish_act.update(d)

print(follow_finish_act)
# prints {6,7,8}
print(list(follow_finish_act))
# prints[8,7,6]

关于python - 如何根据列表中的元素数量停止迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62485382/

相关文章:

spring - 如何在 Spring 中向现有的映射资源或现有的 hbm 列表添加更多的 hbm

python - 在 numpy 中获取平均面积的有效方法

python - 检查数字是否是整个立方体

python - 如何在 Python 中创建具有随机数量的随机整数的列表

python - 如何将包含两个变量的列表 append 到另一个已经包含该列表但具有不同值的列表? Python

list - Sencha 触摸 2.1 : Allowing horizontal overflow on a vertical list

python - 如何在python中的字典列表的字典中对数据进行排序?

python - pyparsing 一个可能包含也可能不包含值的字段

python - 如何从 <select> 标签中抓取更改内容的网页

Python Selenium 'WebDriver' object has no attribute 错误