2 回答
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]
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']
添加回答
举报