python - 如何对列表中的列表执行数学函数

标签 python python-3.x list math nested-lists

我是 python 的新手(使用 python3),我正在尝试将一个列表中的数字添加到另一个列表。唯一的问题是第二个列表是一个列表列表。例如:

[[1, 2, 3], [4, 5, 6]]

我想要的是,比如说,为第一个列表中的每个项目添加 1,为第二个列表中的每个项目添加 2,返回如下内容:

[[2, 3, 4], [6, 7, 8]]

我试过这个:

original_lst = [[1, 2, 3], [4, 5, 6]]
trasposition_lst = [1, 2]
new_lst = [x+y for x,y in zip(original_lst, transposition_ls)]
print(new_lst)

当我这样做时,我得到一个错误

can only concatenate list (not "int") to list

这让我相信,只要列表嵌套在另一个列表中,我就不能以这种方式对列表进行操作。我想在不展平嵌套列表的情况下执行此操作。有解决办法吗?

最佳答案

一种使用枚举的方法

演示:

l = [[1, 2, 3], [4, 5, 6]]
print(  [[j+i for j in v] for i,v in enumerate(l, 1)] )

输出:

[[2, 3, 4], [6, 7, 8]]

关于python - 如何对列表中的列表执行数学函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51027813/

相关文章:

python - 如何从 pandas 的一列中获取不包含在另一列中的 id 列表

python - 将单个整数转换为列表

python - 为什么这个 sqlite3 insert 语句不添加行?

python - Pandas read_excel : nan values forcing others in the same column to be converted to float

python - 如何在我的虚拟环境中使用 Python 3 (3.5) 作为默认解释器?

python - xml.etree.ElementTree findall

python - 用 Scrapy 获取 "ParseError"

python - Unicode 问题,在 python 中正确解码/编码字符串

Python Beautifulsoup Find_all 除了

python - 用逗号连接单词和 "and"