Python 程序可从另一个列表中移除重复元素的索引
当需要从另一个列表中移除重复元素的索引时,会使用“enumerate”属性、列表解析和简单迭代。
示例
以下对此进行说明
my_list_1 = [4, 5, 6, 5, 4, 7, 8, 6]
my_list_2 = [1, 7, 6, 4, 7, 9, 10, 11]
print("The first list is :")
print(my_list_1)
print("The second list is :")
print(my_list_2)
temp_set = set()
temp = []
for index, value in enumerate(my_list_1):
if value not in temp_set:
temp_set.add(value)
else:
temp.append(index)
my_result = [element for index, element in enumerate(my_list_2) if index not in temp]
print("The result is :")
print(my_result)输出
The first list is : [4, 5, 6, 5, 4, 7, 8, 6] The second list is : [1, 7, 6, 4, 7, 9, 10, 11] The result is : [1, 7, 6, 9, 10]
说明
- 定义了两个整数列表并显示在控制台中。
- 创建了一个空集并将其定义为“temp_set”。
- 创建了一个空列表并将其定义为“temp”。
- 使用“enumerate”属性对第一个列表进行迭代,并将第一个列表的元素与第二个列表的元素进行比较。
- 如果它们匹配,则将该元素存储在一个列表中。
- 列表解析用于对第二个列表的元素进行迭代,并检查第二个列表元素的枚举是否出现在新创建的列表中。
- 它被转换为列表。
- 这被分配给一个变量。
- 这以输出的形式显示在控制台中。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP