列表理解混乱

时间:2016-10-04 14:54:26

标签: python

我对我遇到的问题感到有些困惑,并想知道是否有人可以提供帮助(在我看来这似乎微不足道,所以我希望它真的是!)

基本上,我已通过以下列表理解按列表进行过滤:

depfilt = [s for s in department if 'author' not in s]

(部门有154个元素,最终的depfilt有72个元素)

现在,我还有一个单独的iD值列表,其中包含154个元素(subj),其列表的索引与department中的索引相匹配。我希望在过滤过程后保留正确的iD值,因此使用以下代码行:

subfilt = [s for s in subj if 'author' not in department[subj.index(s)]]

在我看来,我觉得这应该有效,但是subfilt实际上返回了106个列表元素,而不是72个。

有人知道为什么吗?

由于

2 个答案:

答案 0 :(得分:7)

如果值重复,请使用enumerate代替index

[s for i, s in enumerate(subj) if 'author' not in department[i]]

答案 1 :(得分:0)

如果departmentsubj肯定属于同一个顺序,即。每个对应的元素匹配,然后使用zip同时迭代两个列表:

[(d, s) for d, s in zip(department, subject) if 'author' not in d]

(对于部门使用d,对主题使用s

这样您就不需要通过索引引用每个元素。只是标准迭代。

编辑:如果你想保持列表分开,那么你可以像你已经拥有dept的第一步,然后像这样修改第二个循环,在循环两个时仍然过滤'author':

[s for d, s in zip(department, subject) if 'author' not in d]

(因此在第二个循环中忽略d的值)

输出示例:

>>> department = ['something', 'else', 'author', 'okay']
>>> subject = ['some_subj', 'else_subj', 'author_subj', 'okay_subj']
>>> [(d, s) for d, s in zip(department, subject) if 'author' not in d]
[('something', 'some_subj'), ('else', 'else_subj'), ('okay', 'okay_subj')]
>>>
>>> # and if you MUST do them seprately:
... [s for s in department if 'author' not in s]  # that's your `deepfilt`
['something', 'else', 'okay']
>>> [s for d, s in zip(department, subject) if 'author' not in d]  # this is for `subfilt`
['some_subj', 'else_subj', 'okay_subj']