Python 中元组记录数据中的交集
当需要找到元组记录数据中的交集时,可以使用列表解析。
列表解析是一种遍历列表并对其执行操作的简写。
列表可用于存储异构值(即任何数据类型的数据,如整数、浮点数、字符串等)。
元组列表实质上包含了列表中封装的元组。下面是相应的演示 −
示例
my_list_1 = [('Hi',1) , ('there',11), ('Will', 56)]
my_list_2 = [('Hi',1) ,('are',7) ,('you',10)]
print("The first list is : ")
print(my_list_1)
print("The second list is : ")
print(my_list_2)
my_result = [elem_1 for elem_1 in my_list_1
for elem_2 in my_list_2 if elem_1 == elem_2]
print("The intersection of the list of tuples is : ")
print(my_result)输出
The first list is :
[('Hi', 1), ('there', 11), ('Will', 56)]
The second list is :
[('Hi', 1), ('are', 7), ('you', 10)]
The intersection of the list of tuples is :
[('Hi', 1)]说明
- 定义了两个元组列表,并显示在控制台上。
- 对这两个元组列表进行迭代,并检查相应元素。
- 如果它们相等,则将其分配给变量。
- 否则它将被忽略。
- 它显示在控制台上。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP