我有以下列表:
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]]
答案 0 :(得分: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 :(得分: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]]