[英]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.