![](/img/trans.png)
[英]ValueError: could not convert string to float: 'F' python
[英]Python: ValueError: could not convert string to float: '4623634 0'
這是我的代碼:
import csv
with open ("Filename1.txt") as f:
dict1 = {}
r = csv.reader(f,delimiter="\t")
for row in r:
a, b, v = row
dict1.setdefault((a,b),[]).append(v)
#for key in dict1:
#print(key[0])
#print(key[1])
#print(d[key][0]])
with open ("Filename2.txt") as f:
dict2 = {}
r = csv.reader(f,delimiter="\t")
for row in r:
a, b, v = row
dict2.setdefault((a,b),[]).append(v)
#for key in dict2:
#print(key[0])
count = 0
for key1 in dict1:
for key2 in dict2:
if (key1[0] == key2[0]) and abs(float(key1[1])) - (float(key2[1])) < 10000:
count += 1
以前我遇到此錯誤:
Traceback (most recent call last):
File "/Users/macbookpro/Desktop/MainDict.py", line 28, in <module>
if key1[0] == key2[0] and abs(key1[1] - key2[1]) < 10000:
TypeError: unsupported operand type(s) for -: 'str' and 'str'
因此,我當然嘗試將這些字符串轉換為整數。 但是我然后收到此錯誤:
Traceback (most recent call last):
File "/Users/macbookpro/Desktop/MainDict.py", line 28, in <module>
if (key1[0] == key2[0]) and abs((int(key1[1])) - (int(key2[1]))) < 10000:
ValueError: invalid literal for int() with base 10: '1002569 1'
然后我嘗試使用float,現在出現此錯誤,這就是我現在遇到的問題:
Traceback (most recent call last):
File "/Users/macbookpro/Desktop/MainDict.py", line 28, in <module>
if (key1[0] == key2[0]) and abs(float(key1[1])) - (float(key2[1])) < 10000:
ValueError: could not convert string to float: '2486997 2'
以下是我的輸入文件組成的示例:
文件名1
1 11383002 8 1.16E-05
1 159962368 1.17E-05
2 133623587 1.26E-05
2 1002569 1 3.30E-06
3 168940139 1.40E-05
3 49736942 1.43E-05
文件名2
10 11383002 8 1.16E-05
5 159962368 1.17E-05
7 133623587 1.26E-05
9 1002569 1 3.30E-06
8 168940139 1.40E-05
1 49736942 1.43E-05
現在我的問題是,為什么會出現此錯誤。 代碼中是否有特定內容? 或者我的文本文件有問題。 您對解決此問題有什么建議?如何更改我的代碼(如果是這種情況)?
我只能猜測應該是什么數字1002569 1
,但是也許可以使用split(" ")[0]
來獲取它的第一部分並將其轉換為int
?
if ... and abs(float(key1[1].split(" ")[0])) - (float(key2[1].split(" ")[0])) < 10000:
如果沒有空間(與其他行一樣),這也將起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.