if __name__ == "__main__":
fptr = open(sys.argv[1], 'r')
for line in fptr:
list1 = []
s = ''
for item in re.findall(r'[\S]+', line):
try:
list1.append(int(item))
except:
s = s + item + ' '
if not len(list1) == 0:
avg = sum(list1) / len(list1)
print(list1)
print(s)
print(avg)
print("{0:.3f} {}".format(avg, s)) //ERROR OCCUR
这是stdout:
[12, 14, 5, 20]
From sample set A
12.75
Traceback (most recent call last):
File "./parse.py", line 28, in <module>
print("{0:.3f} {}".format(avg, s))
ValueError: cannot switch from manual field specification to automatic field numbering
似乎字符串和平均值可以单独打印。但为什么我不能将它们一起打印出来?
答案 0 :(得分:14)
Python抱怨你编号的第一个格式字段而不是第二个格式字段。要么将它们都编号:
print("{0:.3f} {1}".format(avg, s))
# ^ ^
或根本不给他们编号:
print("{:.3f} {}".format(avg, s))
但请注意,第二种解决方案仅适用于Python 2.6或更高版本。