[英]How do I stop iterating based on the number of elements on my list?
I have a project wherein I have to get the follow-up elements of elements in on_time
.我有一个项目,我必须在
on_time
中获取元素的后续元素。
For example:例如:
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]
The code I have looks like this:我的代码如下所示:
# 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
Output I am getting: Output 我得到:
follow_finish_act = [[6, 8], [7, 8]]
Expected Output:预期 Output:
follow_finish_act = [6, 7, 8]
I am having trouble when length of on_time is more than 1. I think the problem is flattening the irregular lists (can be nested and integer) without duplicates.当 on_time 的长度大于 1 时,我遇到了麻烦。我认为问题在于将不规则列表(可以嵌套和整数)展平而没有重复。 Since, I cannot get my expected output.
因为,我无法得到我预期的 output。
Any help/suggestions would be appreciated!任何帮助/建议将不胜感激! Thank you!
谢谢!
Edit: Code I used for trying to flatten output of follow_finish_act编辑:我用于尝试压平 follow_finish_act 的 output 的代码
def flatten(lss):
for item in lss:
try:
yield from flatten(item)
except TypeError:
yield item
Its difficult to tell what you really want, but looking at the code a lot of it seems superfluous.很难说出你真正想要什么,但是看很多代码似乎是多余的。 Try this instead:
试试这个:
j_set = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
s_follow_int = [[2, 3], 4, [5, 6], 8, 7, 9, 8, 10, 10, 11]
on_time = [6, 5]
follow_finish_act = []
for a, d in zip(j_set, s_follow_int):
if a in on_time:
follow_finish_act.append(d)
print(follow_finish_act)
Output: Output:
[7, 9]
If you then get output like: [9]
, you could do this afterwards:如果你然后得到 output 喜欢:
[9]
,你可以这样做之后:
if len(follow_finish_act) == 1:
follow_finish_act = follow_finish_act[0]
You could avoid duplicates by using set
instead of list
您可以通过使用
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.