通过第一列的元素合并矩阵的Python程序
给定一个矩阵,根据第一列中的元素进行合并。
Input : test_list = [[4, “geeks”], [3, “Gfg”], [4, “CS”], [4, “cs”], [3, “best”]]
Output : [[4, ‘geeks’, ‘CS’, ‘cs’], [3, ‘Gfg’, ‘best’]]
Explanation : 4 is paired with geeks, CS and cs hence are merged into 1 row.
Input : test_list = [[4, “geeks”], [3, “Gfg”], [4, “CS”], [5, “cs”], [3, “best”]]
Output : [[4, ‘geeks’, ‘CS’, ‘cs’], [3, ‘Gfg’, ‘best’], [5, ‘cs’]]
Explanation : 4 is paired with geeks and CS hence are merged into 1 row.
方法 1:使用 setdefault() 和列表推导
在这种情况下,分组任务是使用 setdefault() 完成的,它将键分配为第一列元素,其余元素作为列表的值。列表理解用于从构造的字典中获取所有值。
Python3
# initializing list
test_list = [[4, "geeks"], [3, "Gfg"], [4, "CS"],
[4, "cs"], [3, "best"]]
# printing original list
print("The original list is : " + str(test_list))
res = {}
for key, val in test_list:
# setdefault used to merge similar values
res.setdefault(key, []).append(val)
# getting all values
res = [[key] + val for key, val in res.items()]
# printing result
print("Merged Matrix : " + str(res))
Python3
# initializing list
test_list = [[4, "geeks"], [3, "Gfg"], [4, "CS"],
[4, "cs"], [3, "best"]]
# printing original list
print("The original list is : " + str(test_list))
res = {}
for key, val in test_list:
# setdefault used to merge similar values
res.setdefault(key, []).append(val)
# fetch values using value()
res = list(res.values())
# printing result
print("Merged Matrix : " + str(res))
输出:
The original list is : [[4, ‘geeks’], [3, ‘Gfg’], [4, ‘CS’], [4, ‘cs’], [3, ‘best’]]
Merged Matrix : [[4, ‘geeks’, ‘CS’, ‘cs’], [3, ‘Gfg’, ‘best’]]
方法 2:使用 values() 和 setdefault()
在这里,我们使用 values() 提取值,其余所有操作都以与上述类似的方式执行。该程序根据执行的分组从列表中省略了第一列元素。
蟒蛇3
# initializing list
test_list = [[4, "geeks"], [3, "Gfg"], [4, "CS"],
[4, "cs"], [3, "best"]]
# printing original list
print("The original list is : " + str(test_list))
res = {}
for key, val in test_list:
# setdefault used to merge similar values
res.setdefault(key, []).append(val)
# fetch values using value()
res = list(res.values())
# printing result
print("Merged Matrix : " + str(res))
输出:
The original list is : [[4, ‘geeks’], [3, ‘Gfg’], [4, ‘CS’], [4, ‘cs’], [3, ‘best’]]
Merged Matrix : [[‘geeks’, ‘CS’, ‘cs’], [‘Gfg’, ‘best’]]