如何将整个表格从文本转换为整数
我有一个读取的 txt 文件:
fdata =[]
with open(fn,'rb') as fo:
for i in xrange(1):
fo.next()
for line in fo:
data = line.split(',')
data = data[:23]
fdata.append(data)
print fdata
我想将整个表从字符串转换为数字。 AND 将表大小限制为读取 XXX 行。
I have a txt file that I read with:
fdata =[]
with open(fn,'rb') as fo:
for i in xrange(1):
fo.next()
for line in fo:
data = line.split(',')
data = data[:23]
fdata.append(data)
print fdata
I would like convert the entire table to numbers from string. AND limit the table size to read to XXX lines.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要限制行数,请尝试使用计数器和 readlines() 进行迭代:
将字符串转换为数字(在本例中为整数。float() 用于浮点数) :
因此,要使您的表仅包含整数,请将每一行(拆分后)转换为整数。
int()
仅返回一个整数,因此它不会修改您的变量。将fdata.append(data))
替换为fdata.append(int(data()
) 应该可以解决问题。好的,要将整个列表转换为整数,只需迭代即可将这 23 个元素中的每一个都转换为整数,这适用于任意字符串列表:
要将列表转换为整数,但要排除第一个元素,请循环遍历它:
To limit lines, try iterating using a counter and
readlines()
:To convert a string to a number (an integer in this case.
float()
is for floating points):So to make your table only include integers, convert each line (after splitting) into an integer.
int()
only returns an integer, so it doesn't modify your variable. Replacingfdata.append(data))
withfdata.append(int(data()
should do the trick.Okay, to convert your entire list into integers, just iterate over each of those 23 elements to convert them into integers. This works for an arbitrary list of strings:
To convert your list into integers, but to exclude your first element, loop through it: