英文:
Remove duplicate of a list via list matching in Python
问题
我选择了一种稍微不同的方法来移除列表中的重复项。我想在同时保留一个新列表,在其中添加每个重复项。然后,我检查元素是否存在于"新创建的列表"中,以便删除它。
代码如下:
# nums = [1,1,2] or [0,0,1,1,1,2,2,3,3,4]
t = []
nums_new = nums
for i in nums:
if nums[i] not in t:
t.append(nums[i])
else:
nums_new.remove(nums[i])
nums = nums_new
print(nums)
对于nums = [1,1,2]
的情况,这个方法运行正常,并返回[1,2]
。
然而,对于nums = [0,0,1,1,1,2,2,3,3,4]
,这个方法似乎不起作用,因为我得到以下输出:[0, 1, 2, 2, 3, 3, 4]
。
为什么会这样?有人可以解释一下步骤吗?
(Note: The provided code has some issues, and the explanation may not be correct. If you need assistance with fixing the code or understanding the problem, please let me know.)
英文:
I have chosen a slightly different procedure to remove duplicates of a list. I want to keep a new list in parallel, in which each duplicate is added. Afterwards I check if the element is present in the "newly created list" in order to delete it.
The code looks like this:
# nums = [1,1,2] or [0,0,1,1,1,2,2,3,3,4]
t = []
nums_new = nums
for i in nums:
if nums[i] not in t:
t.append(nums[i])
else:
nums_new.remove(nums[i])
nums = nums_new
print(nums)
For the case when nums = [1,1,2]
this works fine and returns [1,2]
.
However, for nums = [0,0,1,1,1,2,2,3,3,4]
this case does not seem to work as I get the following output: [0, 1, 2, 2, 3, 3, 4]
.
Why is this? Can someone explain me the steps?
答案1
得分: 3
以下是要翻译的代码部分:
-
由于你正在遍历一个列表,在
for i in nums
中,i
是实际的数字,而不是索引,所以你应该只使用i
而不是nums[i]
。 -
nums_new = nums
实际上不会创建nums
的副本,而是会创建第二个指向相同列表的绑定。因此,你应该使用nums_new = nums.copy()
,以避免在遍历时更改原始列表。
通过这两个更改,你的代码将按照你的期望工作:
nums = [0,0,1,1,1,2,2,3,3,4]
t = []
nums_new = nums.copy()
for i in nums:
if i not in t:
t.append(i)
else:
nums_new.remove(i)
nums = nums_new
print(nums)
返回 [0,1,2,3,4]
。
当然,这是一种某种学术性的练习,但请注意,从列表中移除重复项的Pythonic方式如下:
- 如果你想保留顺序,可以使用
list(dict.fromkeys(nums))
,以及 - 如果你不关心顺序,可以使用
list(set(nums))
,这是一种略微更快的方法。
英文:
There are two issues with your code:
-
Since you are iterating over a list,
for i in nums
,i
is your actual number, not the indexer, so you should just usei
instead ofnums[i]
. -
nums_new = nums
will not actually make a copy ofnums
, but instead it will make a second binding to the very same list. So you should writenums_new = nums.copy()
to avoid changing your original list while you iterate over it.
With those two changes your code works as you wish:
nums = [0,0,1,1,1,2,2,3,3,4]
t = []
nums_new = nums.copy()
for i in nums:
if i not in t:
t.append(i)
else:
nums_new.remove(i)
nums = nums_new
print(nums)
Returns [0,1,2,3,4]
.
Of course this is an academic exercise of some kind, but note that the Pythonic way to remove duplicates from a list is:
list(dict.fromkeys(nums))
if you want to preserve the order, andlist(set(nums))
for a slightly faster method if you do not care about order.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论