繁体   English   中英

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

[英]How do I use split on spaces and tabulations?

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

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作为键? 我知道我的问题可能很愚蠢,但我被卡住了,真的可以使用一些帮助:) 谢谢! (我们不允许导入除 math、random 之外的任何模块。)

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

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

您可以通过调用 split() 函数轻松拆分字符串。 例如,您有一个字符串并希望将其拆分为一个列表,用逗号分隔单词或在本例中为空格。

string1 = 'This is for an example'

list_of_string1 = string1.split(' ')

所以现在 list_of 字符串变量设置为 ['This', 'is', 'for', 'an', 'example.']

注意 '。' 当您被空格或“ ”分隔时,它仍然存在。 我希望你明白。

假设您正在从文件中逐行读取此行,您可以简单地检查该行是否以:结尾,以确定它是键还是值。

当您看到一个新键时,将其添加到 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)]}

我想这就是你的想法,或者至少接近它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM