如何遍历矩阵并通过计算更改浮点数?

问题描述 投票:0回答:2

我有以下列表:

N_division_n = [0.0, 1.0, 0.4150374992788437]

而且我有以下矩阵:

sample_collection =
[['', 'test1.txt', 'test2.txt', 'test3.txt', 'test4.txt'], 
['apple', 1.0, 1.0, 1.0, 1.0], 
['banana', 1;0, 1.0, 0.0, 0.0], 
['lemon', 1.0, 0.0, 2.0, 1.0]]

我想将矩阵行中的所有值与先前列表中的相应值相乘。像这样:apple values * 0.0, banana values * 1.0, lemon values * 0.4150374992788437

我已经尝试构造以下内容,但是它不想遍历浮点数,并且不确定如何解决它。

def tf_df_calculation(sample_collection):
    for a in range(1,len(sample_collection)):
        tf_df_list = [item[a] for item in N_division_n]
        value_a = 0
        for i in tf_df_list:
            if type(i) is float:
                value_a = i * N_division_n
                sample_collection.append(value_a)

tf_df_calculation(sample_collection)

预期输出:

[['', 'test1.txt', 'test2.txt', 'test3.txt', 'test4.txt'], 
['apple',  0.0, 0.0, 0.0, 0.0], 
['banana',  1.0, 1.0, 0.0, 0.0], 
['lemon',  0.41503749927884376, 0.0, 0.8300749985576875, 0.41503749927884376]]
python python-3.x list matrix
2个回答
1
投票

您在这里:

N_division_n = [0.0, 1.0, 0.4150374992788437]

sample_collection =[['', 'test1.txt', 'test2.txt', 'test3.txt', 'test4.txt'], ['apple', 1.0, 1.0, 1.0, 1.0], ['banana', 1.0, 1.0, 0.0, 0.0], ['lemon', 1.0, 0.0, 2.0, 1.0]]

results = [sample_collection[0]]
count = 0
for sample in sample_collection[1::]:
    calculated_line = [sample[0]] + [x*N_division_n[count] for x in sample[1::]]
    results.append(calculated_line)
    count += 1

输出:

[['', 'test1.txt', 'test2.txt', 'test3.txt', 'test4.txt'], ['apple', 0.0, 0.0, 0.0, 0.0], ['banana', 1.0, 1.0, 0.0, 0.0], ['lemon', 0.4150374992788437, 0.0, 0.8300749985576874, 0.4150374992788437]]

1
投票

这个简单的函数有效,但它使用两个for循环。无论如何,如果矩阵很小,这不是问题。

N_division_n = [0.0, 1.0, 0.4150374992788437]

sample_collection = [['', 'test1.txt', 'test2.txt', 'test3.txt', 'test4.txt'], 
['apple', 1.0, 1.0, 1.0, 1.0], 
['banana', 1.0, 1.0, 0.0, 0.0], 
['lemon', 1.0, 0.0, 2.0, 1.0]]

def tf_df_calculation(sample_collection):
    for a in range(1,len(sample_collection)):
        for b in range(1,len(sample_collection[a])):
            sample_collection[a][b] *= N_division_n[a-1]

tf_df_calculation(sample_collection)

print(sample_collection)

输出

[['', 'test1.txt', 'test2.txt', 'test3.txt', 'test4.txt'], ['apple', 0.0, 0.0, 0.0, 0.0], ['banana', 1.0, 1.0, 0.0, 0.0], ['lemon', 0.4150374992788437, 0.0, 0.8300749985576874, 0.4150374992788437]]
© www.soinside.com 2019 - 2024. All rights reserved.