为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

繁星coding 2023-10-05 17:39:54
我编写了一个生成这样的文件的代码import sysfile = 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,1000.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']我该如何修复它?
查看完整描述

2 回答

?
犯罪嫌疑人X

TA贡献2080条经验 获得超4个赞

首先,在编写 时strlist1,使用 ' ,' 作为分隔符,以避免混淆点是否表示小数点。


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

file.write('\n')

file.write(','.join(strlist1)) # <- note the joining str

当你读回文件时,


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

    data = list(map(int, a.readline().split(','))) # split by the delimiter and convert to int

    data1 = list(map(float, a.readline().split(','))) # same thing but to a float


print(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]


查看完整回答
反对 回复 2023-10-05
?
绝地无双

TA贡献1946条经验 获得超4个赞

您完成了整个过程以使其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):

    try:

        converted_int = int(num)

        return converted_int

    except ValueError:

        return num

        

def convert_float_with_try_except(num):

    try:

        converted_float = float(num)

        return converted_float

    except ValueError:

        return num

        

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']


查看完整回答
反对 回复 2023-10-05
  • 2 回答
  • 0 关注
  • 62 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信