Python 中对列表中元素为列表的每一项求和
-
使用
zip
函数获取具有相应项的元组迭代器。 - 使用列表推导来迭代可迭代对象。
-
在每次迭代中,将元组传递给
sum()
函数。
list_of_lists = [[1, 2], [3, 4], [5, 6]]
# 👇️ [(1, 3, 5), (2, 4, 6)]
print(list(zip(*list_of_lists)))
result = [sum(l) for l in zip(*list_of_lists)]
print(result) # 👉️ [9, 12]
zip
函数并行迭代多个可迭代对象,并生成元组,其中每个可迭代对象都有一个项目。
list_of_lists = [[1, 2], [3, 4], [5, 6]]
# 👇️ [(1, 3, 5), (2, 4, 6)]
print(list(zip(*list_of_lists)))
我们使用 *
可迭代解包运算符在调用 zip()
函数时解包嵌套列表。
list_of_lists = [[1, 2], [3, 4], [5, 6]]
# 👇️ [1, 2] [3, 4] [5, 6]
print(*list_of_lists)
*
可迭代解包运算符使我们能够在函数调用、推导式和生成器表达式中解包可迭代对象。
我们可以想象 zip()
函数迭代嵌套列表,从每个列表中取出一项。
list_of_lists = [[1, 2], [3, 4], [5, 6]]
# 👇️ [(1, 3, 5), (2, 4, 6)]
print(list(zip(*list_of_lists)))
列表中的第一个元组由每个嵌套列表中索引为 0 的元素组成,第二个元组由每个嵌套列表中索引为 1 的元素组成。
最后一步是使用列表推导来迭代 zip
对象并对每个元组求和。
list_of_lists = [[1, 2], [3, 4], [5, 6]]
result = [sum(l) for l in zip(*list_of_lists)]
print(result) # 👉️ [9, 12]
列表推导
用于对每个元素执行一些操作,或者选择满足条件的元素子集。
sum
函数接受一个可迭代对象,从左到右对其项目求和并返回总数。
在每次迭代中,我们将当前元组传递给 sum()
函数并获得总数。
我们可以将此方法用于存储任意长度的嵌套列表的列表。
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# 👇️ [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
print(list(zip(*list_of_lists)))
result = [sum(l) for l in zip(*list_of_lists)]
print(result) # 👉️ [12, 15, 18]
相关文章
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。
使用 Python 将 Pandas DataFrame 保存为 HTML
发布时间:2024/04/21 浏览次数:106 分类:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
如何将 Python 字典转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:73 分类:Python
-
本教程演示如何将 python 字典转换为 Pandas DataFrame,例如使用 Pandas DataFrame 构造函数或 from_dict 方法。
如何在 Pandas 中将 DataFrame 列转换为日期时间
发布时间:2024/04/20 浏览次数:101 分类:Python
-
本文介绍如何将 Pandas DataFrame 列转换为 Python 日期时间。