Python中的文本文件到Tuple to Dictionary

时间:2016-02-05 20:02:04

标签: python

我有一个包含以下信息的文本文件:

Britney 2 3 4 5 1 23 6
Jessica 5 1 5 3 2 33 1 5 2 5 61 2
Mathew 2 33 1 4 2 5 5 2 3 
Sofia 8 3 1 2 3 52 1 5 2 3 51 25 23 1 2 6

我应该编写一个带有名称的函数,并将其指定为dictionary

中的键

关于键的值,这有点复杂。

该功能需要读取数字,FIRST编号(从左到右)表示TUPLE中有多少个数字。然后它通过数字并选择第二个数字 - 第n个数字。

例如。

Britney 2 3 4 5 1 23 6

第一个数字2表示NEXT两个数字将是密钥Britney的元组值。所以布兰妮的价值为(3, 4)

同样地:

Sofia 8 3 1 2 3 52 1 5 2 3 51 25 23 1 2 6

Sofia的值为(3, 1, 2, 3, 52, 1, 5, 2)

我正在思考:

input_file = open("namesandnumbers.txt", "r")
the_dict = {}
for line in input_file:
    initial = line.replace("\n","").split(" ")
    key = initial[0]

但我无法弄清楚下一步该怎么做,我不确定使用split(" "),因为名称和数字之间有空格,但数字本身也是如此。

3 个答案:

答案 0 :(得分:3)

您只需.strip()该行,而不是替换\n。然后只需使用切片:

the_dict = {}

for line in input_file:
    data = line.strip().split()  # no need to specify " ", it will use whitespace already
    key = data[0]
    length = int(data[1])
    data = tuple(data[2:length+2])
    the_dict[key] = data

Bonon one-liner

the_dict = {data[0]:data[2:int(data[1])+2] for data in (line.strip().split() for line in open('somefile'))}

答案 1 :(得分:1)

这对你有用。你走在正确的轨道上,你所缺少的部分就是把绳子切成两半。我建议你在这里阅读更多相关内容:cutting and slicing strings in python

input_file = open("namesandnumbers.txt", "r")
the_dict = {}
for line in input_file:
    initial = line.replace("\n","").split(" ")
    key = initial[0]
    number = int(initial[1])
    value = tuple([int(x) for x in initial[2: number + 2]])
    the_dict[key] = value

答案 2 :(得分:0)

我的两分钱:

data = """Britney 2 3 4 5 1 23 6
Jessica 5 1 5 3 2 33 1 5 2 5 61 2
Mathew 2 33 1 4 2 5 5 2 3 
Sofia 8 3 1 2 3 52 1 5 2 3 51 25 23 1 2 6"""
lst = data.split("\n")
dct = {}
for elem in lst:
    nom, nb, *elem = elem.split(" ")
    dct[nom] = tuple([int(x) for x in elem[:int(nb)]])
print(dct)

结果:

{'Mathew': (33, 1), 'Jessica': (1, 5, 3, 2, 33), 'Sofia': (3, 1, 2, 3, 52, 1, 5, 2), 'Britney': (3, 4)}