首页 > 解决方案 > 在理解列表理解表达式方面需要帮助

问题描述

我正在寻找一种内存有效的方法来从列表中获取唯一数字并遇到以下表达式

used = set()
mylist = [1,2,3,4,3,2,3,4,5,3,2,1]
[x for x in mylist if x not in used and (used.add(x) or True)]

这正在努力获得唯一的数字,但并不完全了解它是如何工作的。下面是我的理解

x for x in mylist  # Iterating through a list
if x not in used  # If statement saying if X not in empty set as defined above
and (used.add(x) or True)  # No idea what it is saying

标签: python

解决方案


x not in used

True如果这是您第一次看到此值,则此表达式返回。所以它变成:

True and (used.add(x) or True)

and由于is的左侧True,它继续评估右侧。这将执行used.add(x), 添加xused集合中。由于.add不返回任何内容,因此or True确保此表达式产生真实值。所以整个if条件导致:

True and (None or True)

这是True,所以是if True,所以这x被保存在列表理解中。

相反,如果这不是您第一次看到该值,则表达式归结为:

x not in used and (used.add(x) or True)
→ False and (used.add(x) or True)
→ False

因此,add没有执行并且整个表达式导致False,所以这x被排除在列表理解之外。

TBH,这是一种相当晦涩的方法,正如这个问题的存在所证明的那样。


推荐阅读