列表理解其他什么都没有 python
list comprehension else nothing python
我试图使用列表理解来添加不在列表中的名称,但我不知道如何使用 else pass
list_test = []
names = ['Gabriel', 'Lucas', 'Pedro', 'Gabriel', 'Fernando'] # To see the 'Ellipsis' just increase this list
# I know that if i use loop 'for ...' this problem could be solved
# but the original code work like this and i can't change it (this part is only a small slice)
count = 0
while True:
if count == len(names): # breaks when all names are read
break
name = names[count] # Just select each name
list_test.append(name if name not in list_test else) # i don't know what put in else to pass
count += 1
print(list_test)
我试过 else ...
但在原始代码中添加 'Ellipsis'
到列表中,在这段代码中有时有效,但我需要更好的解决方案
我希望输出如下:
['Gabriel', 'Lucas', 'Pedro', 'Fernando']
有人可以帮助我吗? ;-
如果您想保留唯一值以便可以转换为字典键并返回列表:
names = ['Gabriel', 'Lucas', 'Pedro', 'Gabriel', 'Fernando']
list_test = list(dict.fromkeys(names).keys())
输出:
['Gabriel', 'Lucas', 'Pedro', 'Fernando']
如果顺序无关紧要,请使用集合:
list_test = list(set(names))
(潜在)输出:
['Lucas', 'Gabriel', 'Pedro', 'Fernando']
我试图使用列表理解来添加不在列表中的名称,但我不知道如何使用 else pass
list_test = []
names = ['Gabriel', 'Lucas', 'Pedro', 'Gabriel', 'Fernando'] # To see the 'Ellipsis' just increase this list
# I know that if i use loop 'for ...' this problem could be solved
# but the original code work like this and i can't change it (this part is only a small slice)
count = 0
while True:
if count == len(names): # breaks when all names are read
break
name = names[count] # Just select each name
list_test.append(name if name not in list_test else) # i don't know what put in else to pass
count += 1
print(list_test)
我试过 else ...
但在原始代码中添加 'Ellipsis'
到列表中,在这段代码中有时有效,但我需要更好的解决方案
我希望输出如下:
['Gabriel', 'Lucas', 'Pedro', 'Fernando']
有人可以帮助我吗? ;-
如果您想保留唯一值以便可以转换为字典键并返回列表:
names = ['Gabriel', 'Lucas', 'Pedro', 'Gabriel', 'Fernando']
list_test = list(dict.fromkeys(names).keys())
输出:
['Gabriel', 'Lucas', 'Pedro', 'Fernando']
如果顺序无关紧要,请使用集合:
list_test = list(set(names))
(潜在)输出:
['Lucas', 'Gabriel', 'Pedro', 'Fernando']