[英]Python (v2.7) format and print
I'm trying to figure out how to print and format the 1st two rows a list that was read in as a csv file and converted to floating point data (Python v2.7). 我试图弄清楚如何打印和格式化第一两行的列表,该列表已作为csv文件读取并转换为浮点数据(Python v2.7)。 Data was then normalized.
然后将数据标准化。 I can print out the rows by using a separate print line for each row, but I cant figure out how to only display say the first 3 places after the decimal point.
我可以通过为每行使用单独的打印行来打印出行,但是我无法弄清楚如何只显示小数点后的前3位。
Depending on what I try I sometimes get error message of : Unknown format code 'f' for object of type 'str' - but the data was converted to floating point - so I don't understand message. 根据我的尝试,有时会收到错误消息:类型为'str'的对象的格式格式为'f'的未知代码-但数据已转换为浮点数-因此我不理解该消息。
Any tips on how to get the first 2 rows printed and formatted ? 关于如何获取前两行的打印格式的任何提示? I have tried looking through here https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions , but couldn't solve anything.
我尝试在这里浏览https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions ,但无法解决任何问题。
# Normalize columns
normalize_dataset(dataset, minmax)
print ('1st row after normalization', dataset[0])
print ('2nd row after normalization', dataset[1])
#for row in range(2):
# print dataset
[format(row, '.3f') for row in dataset]
#print ("Normalization", format(dataset, '.3f'))
Attached is the output when I just print two rows with no formatting using a separate line for each row. 当我仅打印两行而没有使用每一行的单独一行的格式时,输出为附件。 output
输出
Updated with code I am using to convert string to float: 更新了我用来将字符串转换为float的代码:
for i in range(len(dataset[0])):
str_to_float(dataset, i)
def str_to_float(dataset, column):
for row in dataset:
row[column] = float(row[column].strip())
为此使用.format
方法。
print("{0:.2f}".format(dataset))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.