[英]What is the difference between these two list creation codes (one normal for loop with if condition and the other one liner code)
第一个代码使用普通的 for 循环和 if 条件从字符串中创建没有重复成员的数组。
u = []
for l in string:
if l not in u:
u.append(l)
第二个代码做同样的事情,但在一行中。
u = []
u = [l for l in string if l not in u]
一行代码中的条件不起作用,最后, u 始终包含字符串中的所有字符。
使用列表理解方法,条件中的 object u
固定为空列表[]
,因此将始终满足条件:
u = [l for l in string if l not in u] # here u in the condition is always []
使用第一种方法, if l not in u
的条件总是看到更新的u
,因此如果它已经存在,它不会添加元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.