列表理解是否合适?

Pao*_*olo 5 python list-comprehension list duplicates

只有当前迭代元素不在列表中时,我才必须将元素附加到列表中.

>>> l = [1, 2]
>>> for x in (2, 3, 4):
...     if x not in l:
...             l.append(x)
... 
>>> l
[1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

VS

>>> l = [1, 2]
>>> [l.append(i) for i in (2, 3, 4) if i not in l]
[None, None]
>>> l
[1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

列表理解给出了我想要的结果,只是返回的列表是没用的.这是列表推导的一个很好的用例吗?

迭代是一个很好的解决方案,但我想知道是否有更惯用的方法来做到这一点?

Sin*_*ion 7

无论是否具有列表推导,该算法都不尽可能高效; list.__contains__是O(n),因此将另一个列表的元素添加到其中是O(n 2).另一方面,set.__contains__是O(log n),因此最好的方法是使用一个集来检查成员资格,并使用一个列表来保存顺序.这样你就可以进行O(log n)的n次操作,总共为O(n log n),对于合理的n值(比如说100个元素),这比O(n 2)快得多.

>>> l = [1, 2]
>>> seen = set(l)
>>> for x in (2, 3, 4):
...     if x not in seen:
...         seen.add(x)
...         l.append(x)
... 
>>> l
[1, 2, 3, 4]
>>> 
Run Code Online (Sandbox Code Playgroud)


Ger*_*rat 5

你可以这样做:

l.extend((i for i in (2,3,4) if i not in l))
Run Code Online (Sandbox Code Playgroud)

如果添加的列表是非唯一的,则此解决方案仍然有效.

  • @ user772649此代码处理附加的非唯一数字.生成器表达式在`list.extend`中一次评估一个数字,因此在`l`的最新内容上评估条件.试试`l = [1,2]; l.extend(i for i in(2,3,3)如果我不在l)`.如果使用列表推导而不是生成器表达式,则会得到不同的结果. (2认同)