1

.txtからのデータ:

ABC 12 34 24
edf 23 15 63
hre 41 3  356
...
...

(最初の列の)各単語をセットに保存したいと思います。セット内の要素ごとに、その後の各番号を含むリストを作成します。EG word [ABC] [1] = 34、word [hre] [2]=356。

このオンラインに関する有用な情報は見つかりません。

4

3 に答える 3

6

キーを整数のリストにマッピングする辞書が必要になります。

d = {}
with open("input.txt") as f:
    for line in f:
        items = line.split()
        d[items[0]] = map(int, items[1:])
于 2012-04-10T23:32:31.250 に答える
0

これが1つの方法です:

mkt.py

words = {}
with open('a.txt') as f:
  for l in f:
    cols = l.split()
    word = cols[0]
    nums = [int(e) for e in cols[1:]]
    words[word] = nums

# Printing all words with their number lists
for k, v in words.iteritems():
  print("%s -> %s" % (k, v))

# Getting specific ones
print(words['ABC'][1]) # -> 34
print(words['hre'][2]) # -> 356

# Showing it's an int - doing some basic arithmetic operation
i = words['ABC'][1] + 50 # -> 84
print(i)

a.txt

ABC 12 34 24
edf 23 15 63
hre 41 3  356

ランニング:

$ python mkt.py 
hre -> [41, 3, 356]
ABC -> [12, 34, 24]
edf -> [23, 15, 63]
34
356
84
于 2012-04-10T23:39:34.503 に答える
0

これは、大きなファイルでもメモリを節約するためにジェネレータを使用する良い機会です。

ここでは、複数行の文字列を使用してファイルをシミュレートします。

file_ = """ABC 12 34 24
edf 23 15 63
hre 41 3  356""".splitlines()

rows = (line.split() for line in file_)
pairs = ((row[0], map(int, row[1:])) for row in rows)
d = dict(pairs)

for key_ in d:
    print key_, d[key_]

"""
>>>
hre [41, 3, 356]
ABC [12, 34, 24]
edf [23, 15, 63]
"""

print d['ABC'][1]
"34"
于 2012-04-11T00:03:00.903 に答える