Python 列表中元组分组,按第二个元组值匹配
在本教程中,我们将编写一个程序,对列表中所有具有相同第二个元素的元组进行分组。让我们看一个例子来更清晰地理解它。
输入
[('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 'tutorialspoints'), ('React',
'tutorialspoints'), ('Social', 'other'), ('Business', 'other')]输出
{'tutorialspoint': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints'), ('React', 'tutorialspoints')],
'other’: [('Management', 'other'), ('Social', 'other'), ('Business', 'other')]}我们必须对列表中的元组进行分组。让我们看看解决这个问题的步骤。
- 用所需的元组初始化一个列表。
- 创建一个空字典。
- 遍历元组列表。
- 检查元组的第二个元素是否已存在于字典中。
- 如果已存在,则将当前元组追加到其列表中。
- 否则,用包含当前元组的列表初始化键。
- 最后,您将获得一个具有所需修改的字典。
示例
# initializing the list with tuples
tuples = [('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 't
ialspoints'), ('React', 'tutorialspoints'), ('Social', 'other'), ('Business', 'othe
r')]
# empty dict
result = {}
# iterating over the list of tuples
for tup in tuples:
# checking the tuple element in the dict
if tup[1] in result:
# add the current tuple to dict
result[tup[1]].append(tup)
else:
# initiate the key with list
result[tup[1]] = [tup]
# priting the result
print(result)输出
如果您运行上面的代码,则会得到以下结果。
{'tutorialspoints': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints
('React', 'tutorialspoints')], 'other': [('Management', 'other'), ('Social', 'other
'), ('Business', 'other')]}我们使用**defaultdict**跳过了上面程序中的**if**条件。让我们使用**defaultdict**来解决它。
示例
# importing defaultdict from collections
from collections import defaultdict
# initializing the list with tuples
tuples = [('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 't
ialspoints'), ('React', 'tutorialspoints'), ('Social', 'other'), ('Business', 'othe
r')]
# empty dict with defaultdict
result = defaultdict(list)
# iterating over the list of tuples
for tup in tuples:
result[tup[1]].append(tup)
# priting the result
print(dict(result))输出
如果您运行上面的代码,则会得到以下结果。
{'tutorialspoints': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints
('React', 'tutorialspoints')], 'other': [('Management', 'other'), ('Social', 'other
'), ('Business', 'other')]}结论
您可以根据自己的喜好以不同的方式解决它。我们在这里看到了两种方法。如果您对本教程有任何疑问,请在评论部分提出。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP