Python-元组的列求和
Python具有各种库和功能的广泛可用性,因此非常流行用于数据分析。我们可能需要对一组元组的单个列中的值求和以进行分析。因此,在此程序中,我们将一系列元组的相同位置或同一列上存在的所有值相加。
可以通过以下方式实现。
使用for循环和zip
使用for循环,我们遍历每个项目并应用zip函数从每个列中收集值。然后我们应用sum函数,最后将结果放入新的元组中。
示例
data = [[(3, 92), (21, 4), (15, 6)],[(25, 62), (12, 7), (15, 7)]]
print("The list of tuples: " + str(data))
# using list comprehension + zip()result = [tuple(sum(m) for m in zip(*n))
for n in zip(*data)]
print(" Column summation of tuples: " + str(result))输出结果
运行上面的代码将为我们提供以下结果:
The list of tuples: [[(3, 92), (21, 4), (15, 6)], [(25, 62), (12, 7), (15, 7)]] Column summation of tuples: [(28, 154), (33, 11), (30, 13)]
使用映射和邮政编码
我们无需使用for循环和使用map函数即可获得相同的结果。
示例
data = [[(3, 92), (21, 4), (15, 6)],[(25, 62), (12, 7), (15, 7)]]
print("The list of tuple values: " + str(data))
# using zip() + map()result = [tuple(map(sum, zip(*n)))
for n in zip(*data)]
print(" Column summation of tuples: " + str(result))输出结果
运行上面的代码将为我们提供以下结果:
The list of tuple values: [[(3, 92), (21, 4), (15, 6)], [(25, 62), (12, 7), (15, 7)]] Column summation of tuples: [(28, 154), (33, 11), (30, 13)]
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短