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)]
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿