我有一个项目,我必须在 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/