python - 在理解列表理解表达式方面需要帮助
问题描述
我正在寻找一种内存有效的方法来从列表中获取唯一数字并遇到以下表达式
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
解决方案
x not in used
True
如果这是您第一次看到此值,则此表达式返回。所以它变成:
True and (used.add(x) or True)
and
由于is的左侧True
,它继续评估右侧。这将执行used.add(x)
, 添加x
到used
集合中。由于.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,这是一种相当晦涩的方法,正如这个问题的存在所证明的那样。
推荐阅读
- delphi - 为什么 $ff008000 是纯绿色而不是 $ff00FF00?
- c++ - 函数的两个版本不会产生相同的结果
- tensorflow - 如何在训练过程中使用 tensorflow 动态修改神经网络
- angular - 如何在 Angular 应用程序中在运行时按需延迟加载模块?
- machine-learning - 有没有机器学习算法来处理这个问题?
- wso2 - 在 WSO2 AM 上自我注册后如何发送帐户确认电子邮件
- c# - 如何阻止部分继承模型?
- css - 布尔玛图像下拉问题
- google-cloud-functions - 使用 Apple Android 实施登录
- java - 如何在小部件中添加垂直滚动条?