python第2位的值_Python组通过匹配元组列表中的第二个元组值

本教程展示了如何编写一个程序,该程序将列表中的元组按其第二个元素进行分组。通过遍历元组列表并使用字典来存储相同第二个元素的元组,或者使用defaultdict简化这一过程,最终得到一个包含分组结果的字典。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

输入值[('Python', 'nhooos'), ('Management', 'other'), ('Django', 'nhooos'), ('React',

'nhooos'), ('Social', 'other'), ('Business', 'other')]

输出结果{'nhooo': [('Python', 'nhooos'), ('Django', 'nhooos'), ('React', 'nhooos')],

'other’: [('Management', 'other'), ('Social', 'other'), ('Business', 'other')]}

我们必须从列表中对元组进行分组。让我们看看解决问题的步骤。用必需的元组初始化一个列表。

创建一个空字典。

遍历元组列表。检查元组的第二个元素在字典中是否已经存在。

如果已经存在,则将当前元组追加到其列表中。

否则,使用当前元组的列表来初始化键。

最后,您将获得具有所需修改的字典。

示例# initializing the list with tuples

tuples = [('Python', 'nhooos'), ('Management', 'other'), ('Django', 't

ialspoints'), ('React', 'nhooos'), ('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)

输出结果

如果运行上面的代码,则将得到以下结果。{'nhooos': [('Python', 'nhooos'), ('Django', 'nhooos

('React', 'nhooos')], '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', 'nhooos'), ('Management', 'other'), ('Django', 't

ialspoints'), ('React', 'nhooos'), ('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))

输出结果

如果运行上面的代码,则将得到以下结果。{'nhooos': [('Python', 'nhooos'), ('Django', 'nhooos

('React', 'nhooos')], 'other': [('Management', 'other'), ('Social', 'other

'), ('Business', 'other')]}

结论

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值