如何打印输出文件,该文件读取数字列表中的小数位和空格。如果它在逗号和数字之间有多于或少于2个小数位和/或空格,则该数字无效,并将其打印在输出文本文件中。如果它有2个小数位并且数字和逗号之间没有空格,则它是有效数字,并且在输出文本文件中打印I。 输出文件: VALID#仅在float有两个小数位且没有空格的情况下有效 10.34,456.78
INVALID#仅当float的位数小于或等于两个小数位或者为整数或在数字和逗号之间存在空格时,该值才无效 10.345,45.678(空白,并带有3个无花果)
创建一个数字,文件之间用逗号分隔 文本文件:
1,2.12,3.123
1,1.00
它通过有效的sigfig过滤器多少个数字。
from functools import reduce
res = 0
outfile = "output2.txt"
baconFile = open(outfile,"wt")
index = 0
invalid_string = "INVALID"
valid_string = "VALID"
for line in open("file.txt"): #for loop with variable line defined and using open() function to open the file inside the directory
for line in open("file.txt"): #for loop with variable line defined and using open() function to open the file inside the directory
carrera = ''
index = index +1 #adds 1 for every line if it finds what the command wants
print("Line {}: ".format(index))
baconFile.write("Line {}: ".format(index))
with open('file.txt') as file:
number_list = file.readline().strip().split(',')
for line in number_list:
if len(line.split('.')[-1]) == 2:
#res += 1
## print("VALID")
carrera = valid_string
if len(line.split('.')[-1]) != 2:
#res += 1
carrera = invalid_string
print (carrera)
baconFile.write(carrera + " ")
#print(res)
baconFile.close()
#For example, my list looks like this from my text file:
1,2.12,3.123
#Then it print out this to my output text file
output (decimal places from each number):
Line 1: INVALID VALID INVALID
#However, if my list from my text file is like this:
1,2.12,3.123
1,1.00
#Then it print out this to my output text file
output:
Line 1: Line 2: INVALID
VALID
INVALID
Line 3: Line 4: INVALID
VALID
INVALID
#How do I get it to print out like this to my output text file:
Line 1: INVALID VALID INVALID
LINE 2: INVALID VALID
答案 0 :(得分:3)
在您的第一个示例中:
if '.' in number:
res += len(number.split('.')[-1])
您正在计算有效位数,然后将该数字添加到res
中。因此,您当然要获得所有项目的有效位数总数。
如果您只想计算多少个项目的正好两位有效数字,请尝试以下操作:
if '.' in number:
if len(number.split('.')[-1]) == 2:
res += 1