Python - 如何从混合的数字和字符中提取信息并将它们保存在二维列表中?

时间:2012-04-10 23:29:16

标签: python

来自.txt的数据:

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

我想在一组中保存每个单词(在第一列中)。对于集合中的每个元素,都有一个包含其后每个数字的列表。例如。单词[ABC] [1] = 34,单词[hre] [2] = 356。

我在网上找不到任何有用的信息。

3 个答案:

答案 0 :(得分:6)

您需要一个将键映射到整数列表的字典:

d = {}
with open("input.txt") as f:
    for line in f:
        items = line.split()
        d[items[0]] = map(int, items[1:])

答案 1 :(得分: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)

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

答案 2 :(得分: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"