Python 通过匹配元组列表中的第二个元组值进行分组

pythonserver side programmingprogramming更新于 2025/7/23 11:24:17

在本教程中,我们将编写一个程序,将列表中所有具有相同元素作为第二个元素的元组进行分组。让我们看一个例子来清楚地理解它。

输入

[('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')]}

我们必须对列表中的元组进行分组。让我们看看解决问题的步骤。

  • 初始化一个包含所需元组的列表。
  • 创建一个空字典。
  • 遍历元组列表。
    • 检查元组的第二个元素是否已存在于字典中。
    • 如果已存在,则将当前元组附加到其列表中。
    • 否则,使用包含当前元组的列表初始化键。
  • 最后,您将获得一个包含所需修改的字典。

示例

# 使用元组初始化列表
tuples = [('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 't
ialspoints'), ('React', 'tutorialspoints'), ('Social', 'other'), ('Business', 'other
r')]
# 空字典
result = {}
# 遍历元组列表
for tup in tuples:
   # 检查字典中的元组元素
   if tup[1] in result:
      # 将当前元组添加到字典中
      result[tup[1]].append(tup)
   else:
      # 用列表初始化键
      result[tup[1]] = [tup]
# 打印结果
print(result)

输出

如果您运行上述代码,那么您将获得以下结果。

{'tutorialspoints': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints
('React', 'tutorialspoints')], 'other': [('Management', 'other'), ('Social', 'other
'), ('Business', 'other')]}

我们使用defaultdict跳过上述程序中的if条件。让我们使用 defaultdict 来解决这个问题。

示例

# 从集合导入 defaultdict
from collections import defaultdict
# 使用元组初始化列表
tuples = [('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 't
ialspoints'), ('React', 'tutorialspoints'), ('Social', 'other'), ('Business', 'other
r')]
# 使用 defaultdict 清空字典
result = defaultdict(list)
# 遍历元组列表
for tup in tuples:
   result[tup[1]].append(tup)
   # 打印结果
   print(dict(result))

输出

如果您运行上述代码,那么您将获得以下结果。

{'tutorialspoints': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints
('React', 'tutorialspoints')], 'other': [('Management', 'other'), ('Social', 'other
'), ('Business', 'other')]}

结论

您可以按照自己喜欢的方式用不同的方法解决问题。我们在这里看到了两种方法。如果您对本教程有任何疑问,请在评论部分中提及。


相关文章


有用资源