防止将重复项添加到 Python 中的列表

防止在 Python 中将重复项添加到列表中

Prevent adding duplicates to a list in Python

要防止将重复项添加到列表中:

  1. 使用not in运算符检查值是否不在列表中。
  2. 如果该值不在列表中,请使用list.append()方法添加它。
  3. 该列表将不包含任何重复项。
主程序
my_list = ['a', 'b'] value = 'c' if value not in my_list: my_list.append(value) print(my_list) # 👉️ ['a', 'b', 'c'] # ---------------------------------------- my_list = [] values = ['a', 'a', 'b', 'b', 'c', 'c'] for value in values: if value not in my_list: my_list.append(value) print(my_list) # 👉️ ['a', 'b', 'c']

我们使用not in运算符来防止向列表中添加重复项。

in 运算符
测试成员资格

例如,如果是 的成员,则
x in l计算为 ,否则计算为TruexlFalse

x not in l返回 的否定x in l

If the value is not in the list, we use the list.append() method to add it.

The
list.append()
method adds an item to the end of the list.

The method returns None as it mutates the original list.

If you need to prevent adding duplicates to a list while iterating over a
collection of values, use the not in operator on each iteration.

main.py
my_list = [] values = ['a', 'a', 'b', 'b', 'c', 'c'] for value in values: if value not in my_list: my_list.append(value) print(my_list) # 👉️ ['a', 'b', 'c']

We used a for loop to iterate over a list of values.

On each iteration, we check if the current value is not present in the other
list.

If the condition is met, we use the list.append() method to add the value to
the list.

The new list won’t contain any duplicates.

If the order of the elements in the list is not important, consider using a
set object.

Set objects are an unordered collection of unique elements.
main.py
values = ['a', 'a', 'b', 'b', 'c', 'c'] my_set = list(set(values)) print(my_set) # 👉️ ['b', 'a', 'c']

We used the set() class to convert a list to a set object. Since set
objects only store unique values, any duplicates get automatically removed.

However, you should only use this approach if the order of the elements is not important because set objects are unordered.

If you decide to use a set object, you don’t have to check if the value is
already present in the set.

You can directly use the set.add() method because duplicate values cannot be
added to the set.

main.py
jmy_set = set() my_set.add(1) my_set.add(1) print(my_set) # 👉️ {1}

Calling the set.add() method multiple times with the same value has no effect.