Python 使用 numpy 将数组转换为字符串输出
在 Python 中,有时需要将数组转换为字符串输出,但仅需要输出数值部分,而不需要输出数组本身。可以使用 numpy 库中的 tolist() 方法将数组转换为列表,然后使用字符串的 join() 方法将列表中的元素连接成字符串。
例如:
import numpy as np
freq_list = [1, 2, 3, 7, 11, 17, 23, 31, 43, 61, 89, 127, 179, 251, 349]
conductivity_list = [976, 1987, 3850, 5650, 7450, 9238]
conductivity_list.reverse()
for name in ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']:
tumor_result = calculate_conductivity(tumor_dict[name], df_saline_median)
peritumor_result = calculate_conductivity(peritumor_dict[name], df_saline_median)
print(f"Tumor {name}: {', '.join(np.round(tumor_result.tolist(), 2).astype(str))}")
print(f"Peritumor {name}: {', '.join(np.round(peritumor_result.tolist(), 2).astype(str))}")
在这个例子中,np.round() 方法用于将数组中的每个元素保留两位小数,astype() 方法用于将数组中的元素转换为字符串类型。然后使用 join() 方法将列表中的每个元素连接成字符串,用逗号隔开。最后将这个字符串插入到输出语句中。
通过使用这种方法,可以方便地将数组转换为字符串,并将结果输出为仅包含数值的格式。
原文地址: https://www.cveoy.top/t/topic/jJDQ 著作权归作者所有。请勿转载和采集!