Python:ValueError:无法将字符串转换为float:'4623634 0'

时间:2015-07-20 16:13:01

标签: python python-3.x dictionary

这是我的代码:

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'

以下是我的输入文件包含的示例:

FILENAME1

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

现在我的问题是,为什么我会收到此错误。代码中有什么特别的东西吗?或者我的文本文件有问题。你有什么建议来解决这个问题,我怎么能改变我的代码(如果是这样的话)呢?

1 个答案:

答案 0 :(得分:0)

我只能猜出1002569 1应该是多少,但是可以使用split(" ")[0]来获取它的第一部分并将其转换为int

if ... and abs(float(key1[1].split(" ")[0])) - (float(key2[1].split(" ")[0])) < 10000:

如果没有空格(如在其他行中),这也会起作用。