The first code which creates an array with no duplicate members from a string, using a normal for loop and an if condition.
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.
With the list comprehension approach, the object u
in the condition is fixed as the empty list []
so the condition will always be satisfied:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.