Skip to main content
 首页 » 编程设计

python之python中的列表列表,想要对列表中的每个值进行算术运算,然后附加到列表

2025年05月04日13bjzhanghao

我有

expected_values =     
[[name, 4, 8, 3] 
 [name, 2, 6, 9] 
 [name, 3, 6, 2]] 

我想做一些类似于将第二个值除以第一个值,然后将其乘以 3,然后将该值附加到列表末尾的操作。所以最终产品看起来像

expected_values =  
[[name, 4, 8, 3, 6] 
 [name, 2, 6, 9, 9] 
 [name, 3, 6, 2, 6]] 

我目前的情况是

for name in range(0,len(expected_values)): 
    total = 0 
    pa = expected_values[name][1] 
    pa = int(pa) 
    for s in range(0,len(expected_values)): 
        singles = expected_values[s][2] 
        singles = int(singles) 
        total = total + ((singles/pa)*3) 
    expected_values.append(total) 

我有 int(pa) 在那里,因为它是从 CSV 文件导入的,显然它将所有内容都作为字符串导入,所以我必须转换它才能对其进行任何数学运算。

我是 Python 的新手 - 作为一个夏季项目来学习这门语言 - 我对列表中列表的索引有点不稳定,尤其是在这些循环中。

请您参考如下方法:

只需遍历附加 sub[2]/sub[1] * 3 的列表,列表是可变的,append 是 inplace 操作,因此您每次追加时都在修改原始对象/列表,您不需要索引子列表或创建新列表:

expected_values =    [["name", 4, 8, 3], ["name", 2, 6, 9], ["name", 3, 6, 2]] 
 
for sub in expected_values: 
    sub.append(int(sub[2]) / int(sub[1]) * 3) 
 
print(expected_values) 

输出:

[['name', 4, 8, 3, 6], ['name', 2, 6, 9, 9], ['name', 3, 6, 2, 6]] 

您只想确保 sub[2] 元素不是 0 以避免 ZeroDivisionError 并使用默认值或其他值更可取:

for sub in expected_values: 
    a,b = int(sub[1]), int(sub[2]) 
    sub.append(b / a * 3 if b else 0) 
 
print(expected_values) 

sub[2] 提取第一个子列表中的第三个元素,即 8,sub[1] 获取第二个元素,即 4,您只需要乘法和追加即可。

如果您有实际的字符串数字,只需调用 int(sub[2]) 等。根据您想要发生的情况,如果您使用python2,/将在 python 2 中使用整数。