防止在 Python 中将重复项添加到列表中
Prevent adding duplicates to a list in Python
要防止将重复项添加到列表中:
- 使用
not in
运算符检查值是否不在列表中。 - 如果该值不在列表中,请使用
list.append()
方法添加它。 - 该列表将不包含任何重复项。
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
计算为 ,否则计算为。True
x
l
False
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.
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.
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.
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
.
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.