web-dev-qa-db-ja.com

Pythonでファイルから数値を読み取る方法は?

ファイルから数値を2次元配列に読み取りたいです。

ファイルの内容:

  • w、hを含む行
  • スペースで区切られたw個の整数を含むh行

例えば:

4 3
1 2 3 4
2 3 4 5
6 7 8 9
44
kravemir

余分な空白がないと仮定します。

with open('file') as f:
    w, h = [int(x) for x in next(f).split()] # read first line
    array = []
    for line in f: # read rest of lines
        array.append([int(x) for x in line.split()])

最後のforループをネストされたリスト内包に凝縮できます:

with open('file') as f:
    w, h = [int(x) for x in next(f).split()]
    array = [[int(x) for x in line.split()] for line in f]
71
zeekay

私にとって、このような一見単​​純な問題は、Pythonのすべてです。特に、単純なテキスト解析が苦痛になるC++のような言語を使用している場合は、pythonが提供する機能的にユニット単位のソリューションを高く評価するでしょう。いくつかの組み込み関数といくつかのジェネレーター式を使用して、シンプルに保ちます。

open(name, mode)myfile.readlines()mystring.split()int(myval)が必要になります。その後、いくつかのジェネレーターを使用して、それらをすべてPythonic方式でまとめたいと思うでしょう。 。

# This opens a handle to your file, in 'r' read mode
file_handle = open('mynumbers.txt', 'r')
# Read in all the lines of your file into a list of lines
lines_list = file_handle.readlines()
# Extract dimensions from first line. Cast values to integers from strings.
cols, rows = (int(val) for val in lines_list[0].split())
# Do a double-nested list comprehension to get the rest of the data into your matrix
my_data = [[int(val) for val in line.split()] for line in lines_list[1:]]

ジェネレーター式を検索 here 。彼らは本当にあなたのコードを個別の機能ユニットに単純化することができます!同じことをC++の4行で行うと想像してみてください...それは怪物になります。特にリストジェネレーターは、私がC++だったとき、私はいつもそのようなものがあればいいのにと思っていたので、カスタム関数を作成して、必要な各種類の配列を作成することがよくありました。

13

なぜw、hが必要なのかわかりません。これらの値が実際に必要であり、指定された数の行と列のみを読み取る必要がある場合は、次を試すことができます。

output = []
with open(r'c:\file.txt', 'r') as f:
    w, h  = map(int, f.readline().split())
    tmp = []
    for i, line in enumerate(f):
        if i == h:
            break
        tmp.append(map(int, line.split()[:w]))
    output.append(tmp)
3