合肥网站开发培训学校,设计师网上接单被骗,建设旅游网网站软件,h5做的网站有哪些在本教程中#xff0c;我们将编写一个程序#xff0c;该程序将列表中具有与第二个元素相同的元素的所有元组分组。让我们看一个例子来清楚地理解它。输入值[(Python, nhooos), (Management, other), (Django, nhooos), (React,nhooos), (Social, other), (Business, other)]输…在本教程中我们将编写一个程序该程序将列表中具有与第二个元素相同的元素的所有元组分组。让我们看一个例子来清楚地理解它。输入值[(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 tuplestuples [(Python, nhooos), (Management, other), (Django, tialspoints), (React, nhooos), (Social, other), (Business, other)]# empty dictresult {}# iterating over the list of tuplesfor tup in tuples:# checking the tuple element in the dictif tup[1] in result:# add the current tuple to dictresult[tup[1]].append(tup)else:# initiate the key with listresult[tup[1]] [tup]# priting the resultprint(result)输出结果如果运行上面的代码则将得到以下结果。{nhooos: [(Python, nhooos), (Django, nhooos(React, nhooos)], other: [(Management, other), (Social, other), (Business, other)]}我们使用defaultdict跳过上述程序中的if条件。让我们使用defaultdict解决它。示例# importing defaultdict from collectionsfrom collections import defaultdict# initializing the list with tuplestuples [(Python, nhooos), (Management, other), (Django, tialspoints), (React, nhooos), (Social, other), (Business, other)]# empty dict with defaultdictresult defaultdict(list)# iterating over the list of tuplesfor tup in tuples:result[tup[1]].append(tup)# priting the resultprint(dict(result))输出结果如果运行上面的代码则将得到以下结果。{nhooos: [(Python, nhooos), (Django, nhooos(React, nhooos)], other: [(Management, other), (Social, other), (Business, other)]}结论您可以按自己喜欢的方式解决不同的问题。我们在这里看到了两种方式。如果您对本教程有任何疑问请在评论部分中提及。