1

来自 .txt 的数据:

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

我想将每个单词(在第一列中)保存在一组中。对于集合中的每个元素,都有一个包含其后每个数字的列表。例如单词[ABC][1] = 34,单词[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

这是使用生成器来节省内存的好时机,即使是在大文件上也是如此。

在这里,我使用多行字符串模拟文件。

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 回答
0

这是一种方法:

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)

一个.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 回答