Python – 元组列表中的交叉配对

pythonserver side programmingprogramming更新于 2025/10/21 1:48:17

当需要在元组列表中执行交叉配对时,使用‘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("结果列表是:")
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')]

解释

  • 定义两个元组列表,并显示在控制台上。

  • 这两个列表都按升序排序,并显示在控制台上。

  • 两个元组列表被压缩并迭代。

  • 这是使用列表推导完成的。

  • 在这里,比较两个列表的相应元素。

  • 如果它们相等,则将它们存储在列表中并分配给变量。

  • 这显示为控制台上的输出。


相关文章


有用资源