Skip to main content
 首页 » 编程设计

python之如何使用python从文件中读取数字仅列出为整数

2024年12月31日10txw1958

我有一个这样的 txt 文件:

input 0 1 2 3 4 5 6 7 0 
output 127 191 223 239 247 251 253 254 0 

我想将整数 0 1 2 3 4 5 6 7 0 读入列表。 这是我的代码:

f=open('data.txt','r') 
for line in f: 
        if 'input' in line: 
                linestr=line.strip('input') 
                #linestr=list(map(int,linestr) 
                print(linestr) 

输出是

0 1 2 3 4 5 6 7 0 

但是当我添加 "print(linestr[0]+1)" 时,它显示错误 "TypeError: must be str, not int" 这是否意味着我得到的列表仍然不是整数? 如何在此列表中将数字用作 int? 谢谢大家

请您参考如下方法:

它仍然是一个字符串。通过 type(linestr) 进行测试。您不能将整数添加到字符串。

您需要做的是从 liststr 中提取每个值。这可以使用 strip() 轻松完成并遍历此列表以获取每个值,接下来您需要将其传递给 int() 以将每个值转换为整数, 用整数将它附加到你的列表中,然后你就可以按预期使用它了:

new_liststr = [] 
for i in liststr.split(): 
    new_liststr.append(int(i)) 
 
print(new_linestr[0]+1) 

或者作为一个单一的类轮:

new_liststr = [int(i) for i in liststr.split()]  
print(new_linestr[0]+1)