Python——元组列表中的交叉配对
当需要对元组列表进行交叉配对时,可以使用“zip”方法、列表解析和“==”运算符。
例
以下对此进行了演示 −
my_list_1 = [('Hi', 'Will'), ('Jack', 'Python'), ('Bill', 'Mills'), ('goodwill', 'Jill')]
my_list_2 = [('Hi', 'Band'), ('Jack', 'width'), ('Bill', 'cool'), ('a', 'b')]
print("The first list is : " )
print(my_list_1)
print("The second list is :")
print(my_list_2)
my_list_1.sort()
my_list_2.sort()
print("The first list after sorting is ")
print(my_list_1)
print("The second list after sorting is ")
print(my_list_2)
my_result = [(a[1], b[1]) for a, b in zip(my_list_1, my_list_2) if a[0] == b[0]]
print("The resultant list is : ")
print(my_result)输出
The first list is :
[('Hi', 'Will'), ('Jack', 'Python'), ('Bill', 'Mills'), ('goodwill', 'Jill')]
The second list is :
[('Hi', 'Band'), ('Jack', 'width'), ('Bill', 'cool'), ('a', 'b')]
The first list after sorting is
[('Bill', 'Mills'), ('Hi', 'Will'), ('Jack', 'Python'), ('goodwill', 'Jill')]
The second list after sorting is
[('Bill', 'cool'), ('Hi', 'Band'), ('Jack', 'width'), ('a', 'b')]
The resultant list is :
[('Mills', 'cool'), ('Will', 'Band'), ('Python', 'width')]说明
定义了两个元组列表,并显示在控制台上。
这两个列表按照升序排序,并显示在控制台上。
将这两个元组列表进行 zip 并进行迭代。
这是使用列表解析完成的。
在此处比较了这两个列表的各个元素。
如果相等,则将它们存储在列表中并分配给变量。
这是作为控制台上的输出显示的。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP