[英]remove duplicates without using remove or fromkeys;list slicing; python
I'm trying to remove duplicates in a list with iteration and slicing (without .remove
or fromkeys
etc) and keep having wrong result.我正在尝试使用迭代和切片(没有
.remove
或fromkeys
等)删除列表中的重复项,并不断得到错误的结果。
For example now I have a list ['a', 'n', 'a', 'a', 'n']
and by running the following code I keep getting ['a', 'a', 'n']
例如,现在我有一个列表
['a', 'n', 'a', 'a', 'n']
并且通过运行以下代码我不断得到['a', 'a', 'n']
for i in range(1, len(lst)-1):
if lst[i] == lst[0]:
lst = lst[1:]
return lst
I think this is the cause: when there are three elements in the list the range becomes range(1, 2)
which contains nothing.我认为这是原因:当列表中有三个元素时,范围变为
range(1, 2)
,其中不包含任何内容。 But even when I change it to但即使我把它改成
for i in range(len(lst)-1)
which in my opinion makes no sense and should just remove all the elements leaving only the last one ['n']
, it still returns ['a', 'a', 'n']
在我看来这是没有意义的,应该删除所有元素,只留下最后一个
['n']
,它仍然返回['a', 'a', 'n']
Does anyone know the explanation to this?有谁知道对此的解释? Why does it seem stuck in this step?
为什么好像卡在这一步?
You could just put the new elements into a new list
like,您可以将新元素放入一个新
list
例如,
>>> x
['a', 'n', 'a', 'a', 'n']
>>> y = []
>>>
>>> for e in x:
... if e not in y:
... y.append(e)
...
>>> y
['a', 'n']
or just,要不就,
>>> list(set(x))
['n', 'a']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.