[英]How do I check if a string starts with a negative number and a float? [python]
我有一段代碼看起來像這樣:
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
東西是東西,以后會作為值添加到字典中。
您可以嘗試使用try else語句。
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'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.