Python – 元组矩阵中的逐行元素加法
有时,在使用Python元组时,我们可能会遇到需要在元组矩阵中执行 Row-wise 自定义元素添加的问题。这类问题可以在数据域中应用。让我们讨论可以执行此任务的某些方式。
Input :
test_list = [[(‘Gfg’, 3)], [(‘best’, 1)]]
cus_eles = [1, 2]
Output : [[(‘Gfg’, 3, 1)], [(‘best’, 1, 2)]]
Input :
test_list = [[(‘Gfg’, 6), (‘Gfg’, 3)]]
cus_eles = [7]
Output : [[(‘Gfg’, 6, 7), (‘Gfg’, 3, 7)]]
方法 #1:使用enumerate()
+ 嵌套列表推导
上述方法的组合可以用来解决这个问题。在此,我们使用嵌套列表推导和 enumerate() 的索引迭代来执行添加元素的任务。
# Python3 code to demonstrate working of
# Row-wise element Addition in Tuple Matrix
# Using enumerate() + list comprehension
# initializing list
test_list = [[('Gfg', 3), ('is', 3)], [('best', 1)], [('for', 5), ('geeks', 1)]]
# printing original list
print("The original list is : " + str(test_list))
# initializing Custom eles
cus_eles = [6, 7, 8]
# Row-wise element Addition in Tuple Matrix
# Using enumerate() + list comprehension
res = [[sub + (cus_eles[idx], ) for sub in val] for idx, val in enumerate(test_list)]
# printing result
print("The matrix after row elements addition : " + str(res))
The original list is : [[(‘Gfg’, 3), (‘is’, 3)], [(‘best’, 1)], [(‘for’, 5), (‘geeks’, 1)]]
The matrix after row elements addition : [[(‘Gfg’, 3, 6), (‘is’, 3, 6)], [(‘best’, 1, 7)], [(‘for’, 5, 8), (‘geeks’, 1, 8)]]
方法 #2:使用zip()
+ 列表理解
上述功能的组合可以用来解决这个问题。在此,我们使用 zip() 而不是 enumerate() 执行将新行元素与相应行组合的任务。
# Python3 code to demonstrate working of
# Row-wise element Addition in Tuple Matrix
# Using zip() + list comprehension
# initializing list
test_list = [[('Gfg', 3), ('is', 3)], [('best', 1)], [('for', 5), ('geeks', 1)]]
# printing original list
print("The original list is : " + str(test_list))
# initializing Custom eles
cus_eles = [6, 7, 8]
# Row-wise element Addition in Tuple Matrix
# Using zip() + list comprehension
res = [[(idx, val) for idx in key] for key, val in zip(test_list, cus_eles)]
# printing result
print("The matrix after row elements addition : " + str(res))
The original list is : [[(‘Gfg’, 3), (‘is’, 3)], [(‘best’, 1)], [(‘for’, 5), (‘geeks’, 1)]]
The matrix after row elements addition : [[(‘Gfg’, 3, 6), (‘is’, 3, 6)], [(‘best’, 1, 7)], [(‘for’, 5, 8), (‘geeks’, 1, 8)]]