如何获取文件中的 str 作为整数?

我编写了一个生成这样的文件的代码


import sys

file = open('output.txt','w')

x = [1,2,3,4,5,6,7,8,9,10]

f = [i**2 for i in x]

g = [i**3/100 for i in x]


strlist = list(map(str,f))

strlist1 = list(map(str,g))


file.write(','.join(strlist))

file.write('\n')

file.write('.'.join(strlist1))

结果是(文件内容)


1,4,9,16,25,36,49,64,81,100

0.01.0.08.0.27.0.64.1.25.2.16.3.43.5.12.7.29.10.0

我想将此文件作为整数读取以制作这样的列表


[1,4,9,16,25,36,49,64,81,100]

[0.01.0.08.0.27.0.64.1.25.2.16.3.43.5.12.7.29.10.0]

我尝试时遇到此错误


with open('output.txt','r') as a:

    data = a.readlines()[0]



with open('output.txt','r') as a:

    data1 = a.readlines()[1]


intlist = []

intlist.append(data)


['1,4,9,16,25,36,49,64,81,100\n']

['0.01.0.08.0.27.0.64.1.25.2.16.3.43.5.12.7.29.10.0']

我该如何修复它?


繁星coding
浏览 63回答 2
2回答

犯罪嫌疑人X

首先,在编写 时strlist1,使用 ' ,' 作为分隔符,以避免混淆点是否表示小数点。file.write(','.join(strlist))file.write('\n')file.write(','.join(strlist1)) # <- note the joining str当你读回文件时,with open('output.txt','r') as a:&nbsp; &nbsp; data = list(map(int, a.readline().split(','))) # split by the delimiter and convert to int&nbsp; &nbsp; data1 = list(map(float, a.readline().split(','))) # same thing but to a floatprint(data)print(data1)输出:~ python script.py[1, 4, 9, 16, 25, 36, 49, 64, 81, 100][0.01, 0.08, 0.27, 0.64, 1.25, 2.16, 3.43, 5.12, 7.29, 10.0]

绝地无双

您完成了整个过程以使其string由,s 分隔,但没有采取相反的方式。strlist = list(map(str,f))strlist1 = list(map(str,g))a = ','.join(strlist)b = ','.join(strlist1)strlist_as_int = [int(i) for i in a.split(',')]strlist1_as_float = [float(i) for i in b.split(',')]print(strlist_as_int)print(strlist1_as_float)输出:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100][0.01, 0.08, 0.27, 0.64, 1.25, 2.16, 3.43, 5.12, 7.29, 10.0]为了使其成为完整的答案,有时(在真实情况而不是合成情况下),行可以包含非整数或非浮点元素,在这种情况下,最佳实践是错误处理异常,如这里:def convert_int_with_try_except(num):&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; converted_int = int(num)&nbsp; &nbsp; &nbsp; &nbsp; return converted_int&nbsp; &nbsp; except ValueError:&nbsp; &nbsp; &nbsp; &nbsp; return num&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;def convert_float_with_try_except(num):&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; converted_float = float(num)&nbsp; &nbsp; &nbsp; &nbsp; return converted_float&nbsp; &nbsp; except ValueError:&nbsp; &nbsp; &nbsp; &nbsp; return num&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;strlist = list(map(str,f)) + ["not_an_int"]strlist1 = list(map(str,g)) + ["not_a_float"]a = ','.join(strlist)b = ','.join(strlist1)strlist_as_int = [convert_int_with_try_except(i) for i in a.split(',')]strlist1_as_float = [convert_float_with_try_except(i) for i in b.split(',')]print(strlist_as_int)print(strlist1_as_float)输出 - 请注意列表中附加的“非整数”和“非浮点”:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 'not_an_int'][0.01, 0.08, 0.27, 0.64, 1.25, 2.16, 3.43, 5.12, 7.29, 10.0, 'not_a_float']
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python