如何在空间和表格上使用拆分?

2024-06-23 18:47:24 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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']

理想情况下,我希望将该列表转换为字典,但如何选择映射中心峰值作为键?我知道我的问题可能很傻,但我被卡住了,真的需要一些帮助:)谢谢! (除数学、随机等模块外,我们不允许导入任何模块)


Tags: 模块字符串游戏map列表字典编程情况
3条回答

假设您正在从文件中逐行读取该行,只需检查该行是否以:结尾即可确定它是键还是值

当您看到一个新的键时,将其添加到dict中,并将值设置为空列表,但请保留该列表,以便在看到新值时可以继续附加到它

当该行不是键时,可以对其使用split(),并使用列表理解将项目转换为整数。您可以将它们转换为元组,以便为每个键提供一个元组列表

像这样的方法应该会奏效:

result = {}
# initialize `values` to None, so you get an
# error if you see values before a key.
values = None
with open('description.txt') as f:
    for line in f:
        line = line.strip()  # remove newline, spaces
        if not line:
            continue  # skip blank lines
        if line.endswith(':'):
            # it's a key. strip the `:` and start a new list
            values = []
            result[line.rstrip(':')] = values
        else:
            values.append(tuple(int(i) for i in line.split()))

对于初学者来说,这段代码中的一部分可能很奇怪,那就是如何神奇地将值添加到正确的键中。这是因为Python列表是内存中的一个对象,所以将它存储在valuesresults['peaks']中意味着它们都指向同一个列表对象,因此添加到values将正确地将其添加到峰值列表中

列表理解的语法(这里更多的是元组理解)可能看起来也很复杂,但实际上它是一个非常Python的构造,是什么让Python如此易于使用,以及如何能够如此简洁地表达这个复杂的想法

在示例数据上运行此代码会产生以下结果:

{'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()函数,可以轻松拆分字符串。例如,您有一个字符串,希望将其拆分为一个列表,用逗号分隔单词,或者在本例中使用空格

string1 = 'This is for an example'

list_of_string1 = string1.split(' ')

现在字符串变量的列表_被设置为['This','is','for','an','example.]

请注意,当您用空格或“”分隔时,“.”仍然存在。 我希望你能理解

跟踪变量中的最后一个关键点,并在后续行(非关键点)中添加该关键点的值:

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')]
}

相关问题 更多 >

    热门问题