在本教程中,我们将编写一个程序,该程序将列表中具有与第二个元素相同的元素的所有元组分组。让我们看一个例子来清楚地理解它。
输入值[('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', '