我有一个由制表符分隔的文本文件(data.txt),如下所示:
name height weight
A 15.5 55.7
B 18.9 51.6
C 17.4 67.3
D 11.4 34.5
E 23.4 92.1
下面的程序将结果作为字符串列表。
with open('data.txt', 'r') as f:
col1 = [line.split()[0] for line in f]
data1 = col1 [1:]
print (data1)
with open('data.txt', 'r') as f:
col2 = [line.split()[1] for line in f]
data2 = col2 [1:]
print (data2)
with open('data.txt', 'r') as f:
col3 = [line.split()[2] for line in f]
data3 = col3 [1:]
print (data3)
结果如下:
['A', 'B', 'C', 'D', 'E']
['15.5', '18.9', '17.4', '11.4', '23.4']
['55.7', '51.6', '67.3', '34.5', '92.1']
但是,我想将data2和data3作为浮点数列表。 我该如何纠正以上程序? 请帮忙。
答案 0 :(得分:3)
这里不需要读取文件3次,你可以通过定义一个简单的函数来做到这一点,如果它是一个有效的数字,则返回该项的浮点值,否则按原样返回。
现在使用列表推导逐个读取所有行,并将此函数应用于每行的项目。现在您已经有了一个列表列表,现在是时候使用zip(*)
解压缩该列表列表,并将返回值分配给data1
,data2
,data3
def ret_float(x):
try:
return float(x)
except ValueError:
return x
with open('data.txt') as f:
next(f) #skip the header
lis = [ map(ret_float,line.split()) for line in f]
#[['A', 15.5, 55.7], ['B', 18.9, 51.6], ['C', 17.4, 67.3], ['D', 11.4, 34.5], ['E', 23.4, 92.1]]
#unzip the list
data1, data2, data3 = zip(*lis)
#if you want data1,data2,data3 to be lists then use:
#data1, data2, data3 = [list(x) for x in zip(*lis)]
...
>>> data1
('A', 'B', 'C', 'D', 'E')
>>> data2
(15.5, 18.9, 17.4, 11.4, 23.4)
>>> data3
(55.7, 51.6, 67.3, 34.5, 92.1)
更新:修复解决方案
with open('data.txt', 'r') as f:
col2 = [line.split()[1] for line in f]
data2 = list(map(float, col2 [1:])) # apply float to each item using `map`
# as `map` returns a `map` object in py3.x
# you have to pass it to list()
with open('data.txt', 'r') as f:
col3 = [line.split()[2] for line in f]
data3 = list(map(float, col3 [1:]))
print (data3)
map
上的帮助:
>>> print(map.__doc__)
map(func, *iterables) --> map object
Make an iterator that computes the function using arguments from
each of the iterables. Stops when the shortest iterable is exhausted.
答案 1 :(得分:0)
使用float()
功能。它需要1个arg,这将是你想要变成浮点数的字符串/ var。
答案 2 :(得分:0)
使用float()
命令:
with open('data.txt', 'r') as f:
col2 = [float(line.split()[1]) for line in f]
data2 = col2[1:]
print(data2)
答案 3 :(得分:0)
在阅读时将字符串转换为float
:
data1 = col1 [1:]
变为
data1 = float(col1 [1:])
但是 - 我知道你没有问过这个问题 - 你的做法有点侧面。您可能想要考虑更像这样的程序结构:
data0 = []
data1 = []
data2 = []
with open('data.txt', 'r') as f:
f.readline()
for line in f:
vals = line.split()
data0.append(vals[0])
data1.append(vals[1])
data2.append(vals[2])
print(data0)
print(data1)
print(data2)
希望它有所帮助!
(免责声明:适用于Python 2.7;不确定3.x。)
答案 4 :(得分:0)
with open('data.txt', 'r') as f:
col1 = [line.split()[0] for line in f]
data1 = col1 [1:]
print (data1)
with open('data.txt', 'r') as f:
col2 = [line.split()[1] for line in f]
data2 = float(col2 [1:])
print (data2)
with open('data.txt', 'r') as f:
col3 = [line.split()[2] for line in f]
data3 = float(col3 [1:])
print (data3)