英文:
Removing adjacent elements in a list
问题
尝试编写一个函数来移除列表中相邻相同的元素。所以[1,2,3,3,4]会返回[1,2,3,4]。
我的代码如下:
```python
def remove_adjacent(nums):
for i in nums:
if i == nums[nums.index(i)-1]:
nums = nums.remove(i)
return nums
结果返回原始列表没有修改。有人可以告诉我原因吗?
<details>
<summary>英文:</summary>
Trying to write a function to remove adjacent identical elements in a list. So [1,2,3,3,4] would return [1,2,3,4]
My codes as below:
def remove_adjacent(nums):
for i in nums:
if i == nums[nums.index(i)-1]:
nums = nums.remove(i)
return nums
The result is returning the original list without modifying. Can someone educate me why?
</details>
# 答案1
**得分**: 1
`if`块永远不会运行`remove_adjacent([1, 2, 3, 3, 4])`。
`nums.index(i)`将始终返回第一个匹配的索引。当`i`是`3`(两者之一的三)时,`nums.index(i)`将返回`2`,因此`nums[nums.index(i)-1]`将是`nums[2 - 1]`将是`2`,而`3 == 2`将是`False`。
因此,`return nums`只是返回未经修改的列表。
<details>
<summary>英文:</summary>
The `if` block never runs for `remove_adjacent([1, 2, 3, 3, 4])`.
`nums.index(i)` will always give the first matching index. When `i` is `3` (either of the threes), `nums.index(i)` will return `2`, so `nums[nums.index(i)-1]` will be `nums[2 - 1]` will be `2`, and `3 == 2` will be `False`.
Therefore, `return nums` just returns the list, unmodified.
</details>
# 答案2
**得分**: 1
根据@TomKarzes的评论,你的逻辑存在几个问题:
- 在修改列表的同时,你正在遍历它
- 你遍历项目,并尝试用`index`获取它们的索引,这是没有意义的。如果你需要遍历索引,直接这样做。
- 即使你在遍历列表时没有移除项目,`index`只会找到一个项目的**第一个**出现。
使用循环的一个选项可以是:
```python
def remove_adjacent(nums):
out = []
prev = None
for num in nums:
if num != prev:
out.append(num)
prev = num
return out
remove_adjacent([1, 2, 3, 3, 4])
# [1, 2, 3, 4]
注:如果你想在原始列表上进行原地更新,请将 return out
替换为 nums[:] = out
。
另一个选择是使用 itertools.groupby
:
from itertools import groupby
out = [k for k, _ in groupby(nums)]
英文:
Following @TomKarzes comment, there are several flaws in your logic:
- you are iterating over the list while modifying it
- you iterate over the items, and try to get their index with
index
which is a nonsense. If you need to iterate over indices just do that. - even if you did not remove items while iterating over the list,
index
only finds the first occurrence of an item.
One option with a loop could be:
def remove_adjacent(nums):
out = []
prev = None
for num in nums:
if num != prev:
out.append(num)
prev = num
return out
remove_adjacent([1, 2, 3, 3, 4])
# [1, 2, 3, 4]
NB. If you want to update the original list in place, replace return out
by nums[:] = out
.
Another option could be to use itertools.groupby
:
from itertools import groupby
out = [k for k, _ in groupby(nums)]
答案3
得分: 0
问题在于你尝试使用函数 array.index(i)
。请查看文档。index
返回第一次出现的索引,所以当你的迭代器等于第二个3时,index
返回的是2,而不是3。在你的条件语句中,你会得到这样的结果:3 == nums[1]
,其中 nums[1] == 2
。我会这样解决这个问题:
def remove_adjacent(nums):
for i in range(len(nums) - 1, 0, -1):
if nums[i] == nums[i - 1]:
del nums[i]
return nums
英文:
A problem is that you try to use function array.index(i). Check the documentation. Index returns index of the first occurrence, so when your iterator equals to second 3, index returns index 2 instead of 3. And you get this in your if statement: 3 == nums[1]
, where nums[1] == 2
. I would solve this problem this way:
def remove_adjacent(nums):
for i in range(len(nums) - 1, 0, -1):
if nums[i] == nums[i - 1]:
del nums[i]
return nums
答案4
得分: 0
首先,索引将仅获取第一个匹配的出现次数,所以要避免使用它。
其次,为了比较,你需要保留先前看到的值,并在每次迭代结束时更新它。
第三,remove方法直接在列表上进行更新,所以无需重新分配nums为删除列表,事实上它只是破坏了列表。
最终的代码如下:
x = [1, 2, 3, 3, 4]
def remove_adjacent(nums):
previous = nums[0]
for i in nums:
if previous == i and i != nums[0]:
nums.remove(i)
previous = i
return nums
remove_adjacent(x)
英文:
firstly index will fetch only the first matching occurrence so avoid that.
secondly to compare you need to retain the previously seen value and update it at the end of every iteration.
thirdly remove method directly updates on the list itself so no need to reassign nums with remove list,in fact it only destroys the list.
the final code is given below
x=[1,2,3,3,4]
def remove_adjacent(nums):
previous=nums[0]
for i in nums:
if previous==i and i!=nums[0]:
nums.remove(i)
previous=i
return nums
remove_adjacent(x)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论