从列表中删除重复元素而不创建新列表。

huangapple go评论81阅读模式
英文:

remove duplicate elements from list without creating new list

问题

我正在尝试使用for循环从列表中删除元素不创建新列表或使用set()等函数)。

我编写了以下代码但出现了IndexError: list index out of range

我错过了什么

```python
MyList=[1,1,2,3]

for i in MyList:
   for j in MyList:
      if MyList[i] == MyList[j]:
         del MyList[j]
      else:
         j = j+1
         i = i+1

print(MyList)

我期望得到一个没有重复元素的相同列表


<details>
<summary>英文:</summary>

I&#39;m trying to remove an element from a list using for loops (without creating new list or functions like set()..etc)

I wrote the below code but I got: IndexError: list index out of range.

what I missing?


MyList=[1,1,2,3]

for i in MyList:
for j in MyList:
if MyList[i] == MyList[j]:
del MyList[j]
else:
j = j+1
i = i+1

print(MyList)


I expect to get same list without duplicate elements

</details>


# 答案1
**得分**: 2

你之所以出现索引错误是因为你正在使用项目值作为索引。`for i in myList:`将项目值(而不是索引)放入变量`i`中。所以在`MyList[i] == MyList[j]`中使用`i`作为索引是行不通的。

为了获得索引,你需要使用`range()`或`enumerate()`函数(或手动增加一个变量)。

避免在列表迭代中移除项的干扰的一种方法是从后向前工作。

例如(使用你自己的索引变量):

```python
i = len(myList)-1             # 当前项目索引(从最后开始)
for n in reversed(myList):    # 反向迭代
    if myList.index(n) < i:   # 如果n是早期项目的重复项
        del myList[i]         # 删除重复项
    i -= 1                    # 上一个索引

另一种方法可能是将不是重复项的项目移到列表开头,并在循环结束时删除额外的位置:

j = 0                          # 下一个唯一项目的位置
for n in myList:               # 遍历项目
    if myList.index(n) >= j:   # 尚未在列表开头
        myList[j] = n          # 将其放在开头 
        j += 1                 # 下一个唯一位置
myList[j:] = []                # 删除额外的空间
英文:

You are getting an indexing error because you are using item values as indexes. for i in myList: places item values (not indexes) in the i variable. So using i as an index in MyList[i] == MyList[j] cannot work.

In order to get indexes, you need to use the range() or enumerate() function (or increase a variable manually).

One way to avoid interference of removals on the list iteration is to work your way backward.

For example (using your own indexing variable):

i = len(myList)-1             # current item index (starting from last)
for n in reversed(myList):    # iterate backward
    if myList.index(n) &lt; i:   # if n is duplicate of earlier item
        del myList[i]         #    remove the duplicate
    i -= 1                    # previous index

Another approach could be to move items that are not duplicates at the beginning of the list and delete the extra positions at the end of the loop:

j = 0                          # next position of unique item
for n in myList:               # go through items
    if myList.index(n) &gt;= j:   # not already at beginning of list
        myList[j] = n          # place it at beginning 
        j += 1                 # next unique position
myList[j:] = []                # delete extra space

答案2

得分: 0

我希望这对你有用

MyList=[1, 1, 2, 3]

for number in MyList:
repeated = MyList.count(number)
if repeated > 1:
MyList.remove(number)
print(MyList)

结果将会是: [1, 2, 3]

英文:

I hope this works for you

MyList=[1, 1, 2, 3]

    for number in MyList:
        repeated = MyList.count(number)
        if repeated &gt; 1:
            MyList.remove(number)
    print(MyList)

The result will be: [1, 2, 3]

huangapple
  • 本文由 发表于 2023年7月23日 19:54:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76748086.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定