![](/img/trans.png)
[英]Read the file line-by-line and use the split() function to break the line into a list of integers using python
[英]Python how to read and split a line to several integers
對於由空格/制表符分隔的輸入文件,如:
1 2 3
4 5 6
7 8 9
如何讀取行並拆分整數,然后保存到列表或元組中? 謝謝。
data = [[1,2,3], [4,5,6], [7,8,9]]
data = [(1,2,3), (4,5,6), (7,8,9)]
一種方法,假設子列表位於不同的行上:
with open("filename.txt", 'r') as f:
data = [map(int, line.split()) for line in f]
請注意,在Python 2.6之前, with
語句才成為官方聲明。 如果您使用的是早期版本,則需要執行此操作
from __future__ import with_statement
如果你發現自己處理矩陣或數字表,我可以建議numpy包嗎?
import numpy as np
data = np.loadtxt(input_filename)
tuples = [tuple(int(s)for s in line.split())for line in open(“file.txt”)。readlines()]
我喜歡傑夫的map(int, line.split())
,而不是內部生成器。
你的意思是,像這樣?
更新
只需將每個字符串轉換為int
string = """1 2 3
4 5 6
7 8 9"""
data = []
for line in string.split("\n"): #split by new line
data.append( map( int, line.split(" ") ) ) # split by spaces and add
print( data )
輸出:
[['1','2','3'],['4','5','6'],['7','8','9']]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Da daaaa !!!
def getInts(ln):
return [int(word) for word in ln.split()]
f = open('myfile.dat')
dat = [getInts(ln) for ln in f]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.