例如下面的列表
l=[1, 2, 3, 'hello', "world", True, 10, 1, 2, 3, 'hello', True, 10, 1, 2, 3, 'hello', True] ,
我无法保留关键字True的出现。我使用了诸如for循环之类的不同方法来遍历列表中的每个元素,如果新列表中不存在该元素,则将其追加到新列表中(天真的方法),列表理解,内置函数set()。
我得到下面的输出是不正确的!
[1, 2, 3, 'hello', 'world', 10]
请协助我解决这个问题
我写的代码
ll=[]
for i in l :
if i not in ll :
ll.append(i)
print(ll)
我得到的输出= [1,2,3,'hello','world',10]预期的输出= [1,2,3,'hello','world',True,10]
问题在于,1 == True
对象相等性包含检查测试。您还必须测试类型相等性:
l = [1, 2, 3, 'hello', "world", True, 10, 1, 2, 3, 'hello', True, 10, 1, 2, 3, 'hello', True]
no_dupes = [x for x, _ in {(x, type(x)) for x in l}]
# [2, 3, 10, True, 1, 'world', 'hello']
或者,调整您的循环方法(保留发生顺序):
ll = []
s = set()
for i in l:
if (i, type(i)) not in s:
s.add((i, type(i)))
ll.append(i)
print(ll)
# [1, 2, 3, 'hello', 'world', True, 10]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句