列表列表中元素的乘法

2024-06-28 20:02:38 发布

您现在位置:Python中文网/ 问答频道 /正文

您好,我正在尝试将列表中的某些列表乘以变量

假设我有以下几点

[['', 'header1.txt', 'header2.txt', 'header3.txt', 'header4.txt'],
 ['cow', 4, 3, 2, 10],
 ['pig', 20, 4, 7, 2]]

以及以下变量:

cows = 2
pigs = 4

如何将cow列表乘以变量cow,将pig列表乘以变量pig来创建

[['', 'header1.txt', 'header2.txt', 'header3.txt', 'header4.txt'],
 ['cow', 8.0, 6.0, 4.0, 4.0],
 ['pig', 80.0, 16.0, 28.0, 8.0]]

它不必是浮动的,但这将是理想的。 我用这种东西试过了

matrix = [['', 'header1.txt', 'header2.txt', 'header3.txt', 'header4.txt'],
          ['cow', 4, 3, 2, 10],
          ['pig', 20, 4, 7, 2]]
cows = 2
pigs = 4
weightmatrix = []

for value in matrix:
    try:
        weightmatrix.append(matrix[1]*cows)
        weightmatrix.append(matrix[2]*pigs)
    except:
        pass
print(weightmatrix)

但是对我来说,这会在每个列表中创建两倍的元素,它似乎只是将列表相互复制和粘贴,而不是将值相乘


Tags: txt列表formatrix理想pigappendcow
2条回答

当您获得匹配项时,需要分别替换列表中的每个项。你不能把整张单子放大

为了方便起见,我还建议将操作放入dict

matrix = [
    ['', 'header1.txt', 'header2.txt', 'header3.txt', 'header4.txt'],
    ['cow', 4, 3, 2, 10],
    ['pig', 20, 4, 7, 2],
]
ops = {
    'cow': 2,
    'pig': 4,
}

for row in matrix:
    if row[0] in ops:
        for i in range(1, len(row)):
            row[i] *= ops[row[0]]

以下是我解决问题的方法:

matrix = [['', 'header1.txt', 'header2.txt', 'header3.txt', 'header4.txt'],
          ['cow', 4, 3, 2, 10],
          ['pig', 20, 4, 7, 2]]
multipliers = {
    "cow": 2,
    "pig": 4,
}

for i, row in enumerate(matrix):
    m = multipliers.get(row[0])
    if m is not None:
        matrix[i] = [row[0]] + [x * m for x in row[1:]]

相关问题 更多 >