首页 > 解决方案 > 如何在空格和表格上使用拆分?

问题描述

我目前正在尝试为我的编程课程创建一个游戏。但是,我不知道如何拆分以下字符串序列:

map:
39 41
hubs:
21 3 1500 25
21 38 1500 25
peaks:
10 10 200
11 10 300
12 10 400
10 11 200
10 12 500

拆分后,我会留下一个列表,但我无法使用它。

['map:', '39', '41', 'hubs:', '21', '3', '1500', '25', '21', '38', '1500', '25', 'peaks:', '10', '10', '200', '11', '10', '300', '12', '10', '400', '10', '11', '200', '10', '12', '500']

理想情况下,我想将该列表转换为字典,但如何选择maphubspeaks作为键?我知道我的问题可能很愚蠢,但我被困住了,真的可以使用一些帮助:) 谢谢!(除了数学,随机,我们不允许导入任何模块。)

标签: pythonstringlistsplitkey

解决方案


跟踪变量中的最后一个键并在后续行(不是键)中添加该键的值:

lines = """map:
39 41
hubs:
21 3 1500 25
21 38 1500 25
peaks:
10 10 200
11 10 300
12 10 400
10 11 200
10 12 500""".split("\n")

# with open('plateau.txt','r') as f:
#     lines = f.read().split("\n")

d = dict()
currentKey = None
for line in lines:
    if ":" in line:
        currentKey    = line.strip(":")
        d[currentKey] = []
    else:
        d[currentKey].append(tuple(line.split(" ")))

结果:

print(d)

{
   'map':   [('39', '41')],
   'hubs':  [('21', '3', '1500', '25'), ('21', '38', '1500', '25')],
   'peaks': [('10', '10', '200'), ('11', '10', '300'), ('12', '10', '400'),
             ('10', '11', '200'), ('10', '12', '500')]
}

推荐阅读