3

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

2 回答 2

1

很难说出你真正想要什么,但是看很多代码似乎是多余的。试试这个:

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)

输出:

[7, 9]

如果您随后得到类似的输出:[9],您可以在之后执行此操作:

if len(follow_finish_act) == 1:
    follow_finish_act = follow_finish_act[0]
于 2020-06-20T11:53:27.133 回答
1

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]
于 2020-06-20T13:29:14.753 回答