我有一段看起来像这样的代码:
loc2 = {}
with open('loc.txt') as filename:
for line in filename:
a = line.strip()
if a.replace('.','',1).isdigit():
loc2[float(a[0])] = a[1:]
return loc2
其中我需要检查一个数字 [它总是在文件 loc.txt 中的行的开头,并且总是单独在整行中] 可以是负数、整数或浮点数,并将其添加到字典作为键。有人可以帮我吗?不知道如何处理这个。我尝试替换'.' 有空的空间,但它没有用,也没有解决我的负数问题,显然。我仍然是 python 的菜鸟。谢谢!
loc.txt 的示例:
1
stuff
1.1
stuff
-4
stuff
其中 stuff 是稍后将作为值添加到字典中的内容。
您可以尝试使用 try except 语句。
loc2 = {}
with open('loc.txt') as filename:
for i,line in enumerate(filename):
# split the given line up by space into a list
a = line.strip().split()
try:
# attempt to convert first part of line into float
k = float(a[0])
# assignment that key the value of the rest of the string
loc2[k] = ' '.join(a[1:])
except ValueError as ex:
# actions performed when the line does not start with number
print('Line %d did not start with a number.'%i)
else:
# actions performed when the float conversion was successful
print('Key {} has been added with value: {}'.format(k,loc2[k]))
loc.txt 文件:
-1 one
0 two
1.5 three
-5.708 four
test
输出:
Key -1.0 has been added with value: one
Key 0.0 has been added with value: two
Key 1.5 has been added with value: three
Key -5.708 has been added with value: four
Line 4 did not start with a number.
loc2 内容
{-1.0: 'one', 0.0: 'two', 1.5: 'three', -5.708: 'four'}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句