简体   繁体   English

这两个列表创建代码有什么区别(一个是带有 if 条件的普通 for 循环,另一个是线性代码)

[英]What is the difference between these two list creation codes (one normal for loop with if condition and the other one liner code)

The first code which creates an array with no duplicate members from a string, using a normal for loop and an if condition.第一个代码使用普通的 for 循环和 if 条件从字符串中创建没有重复成员的数组。

u = []
for l in string:
    if l not in u:
        u.append(l)

And the second code which does the same thing but in one line.第二个代码做同样的事情,但在一行中。

u = []
u = [l for l in string if l not in u]

The condition in the one line code is not working and at the end, u always contains all the characters in string.一行代码中的条件不起作用,最后, u 始终包含字符串中的所有字符。

With the list comprehension approach, the object u in the condition is fixed as the empty list [] so the condition will always be satisfied:使用列表理解方法,条件中的 object u固定为空列表[] ,因此将始终满足条件:

u = [l for l in string if l not in u] # here u in the condition is always []

With the first approach, the condition if l not in u always see the updated u so it doesn't add the element if it is already present.使用第一种方法, if l not in u的条件总是看到更新的u ,因此如果它已经存在,它不会添加元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM