简体   繁体   English

Python列表未转换为整数

[英]Python list not converting into a integer

Hi I'm trying to convert my file back into a integer, the file reads numbers but is stored in a string and I'm trying to convert it into a integer the error I keep getting is: 嗨,我正在尝试将文件转换回整数,该文件读取数字但存储在字符串中,并且我试图将其转换为整数,但我一直遇到的错误是:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list' TypeError:int()参数必须是字符串,类似字节的对象或数字,而不是“列表”

My code: 我的代码:

with open('Position_of_Words.txt') as d:    #my file 
    for line in d:
        print (int(line)) #Trying to convert into a integer


position_of_words_list = line.split(" ")  #make into list
print (position_of_words_list)  

You are trying to convert whole string to integer. 您正在尝试将整个字符串转换为整数。

First split that string, then cast integer on each item. 首先拆分该字符串,然后在每个项目上强制转换为整数。

with open('Position_of_Words.txt') as d:    #my file 
    for line in d:
        if line: #checks if line is not empty    
            position_of_words_list = list(map(int, line.split())) 
            print (position_of_words_list)

#since there is only one line in txt file, you can also use something like below
with open("input.txt","r") as f:
    position_of_words_list  = list(map(int, f.read().split()))
    print position_of_words_list 

Since you have only one line, above should work. 由于您只有一行,因此上面应该可以。 If there are more than one line, you can append each line into the list. 如果有多行,则可以将每行追加到列表中。

position_of_words_list = [] #which will be list of lists
with open('Position_of_Words.txt') as d:    #my file 
    for line in d:
        if line: #checks if line is not empty    
            position_of_words_list.append(list(map(int, line.split())))
    print (position_of_words_list)

Since the file has only one line and the line read as string you are getting that error. 由于文件只有一行,并且该行读为字符串,因此您将收到该错误。

with open('t.txt','r') as d:
    for line in d:
        position_of_words_list = [int(i) for i in line.split(' ')]
    print position_of_words_list

Maybe is error in formatting the code, but the line variable is not inside the for block. 也许在格式化代码时出错,但是line变量不在for块内。

Also, if you have spaces in the lines you cannot convert it into int. 另外,如果行中有空格,则无法将其转换为int。 It will only work if the line is a string with numbers only (no letter or any other special char like spaces). 仅当该行是仅包含数字的字符串(没有字母或任何其他特殊的字符,如空格)时才有效。

Concerning the error itself, it looks like the iterator is converting the line into a list (probably of bytes?). 关于错误本身,看起来迭代器正在将行转换为列表(可能是字节?)。 Try to use str(line). 尝试使用str(line)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM