0

我正在按照教程创建文本冒险,我现在正在创建部分,但还没有完成,但有些东西我就是不明白。所以,我正在为这些部分创建一个数组。该数组包括描述和名称。现在该部分的名称有一个降低它的代码,用 - 替换空格。它会删除句号和撇号。然后将其放入一个名为 sec 的数组中。这是我不明白的部分:

sec = {}
for indexed in enumerate(sections):
    index = indexed[0]
    long_name = indexed[1][1]
    short_name = ''
    for C in long_name:
        if C == ' /':
            short_name += '-'
        elif not C == ".'":
            short_name += C.lower()
    sec[short_name] = index

这是我的全部代码:

    import time
import random
sections = [
    (
        """You are in front of your friend's house. Your friend's house is
(n)orth and the driveway is south. There is a mailbox next to you.""",
        "Front Of Friend's House"), #0
    (
        """You are in your friend's house. Northwest is the stairs, the
kitchen is up north, the door is south. Your friend is upstairs.""",
        "Friend's house"), #1
    (
        """You are upstairs, the bathroom is up north, your friend's bedroom
is west. The stair down is south.""",
        "Friend's house upstairs"), #2
    ]

sec = {}
for indexed in enumerate(sections):
    index = indexed[0]
    long_name = indexed[1][1]
    short_name = ''
    for C in long_name:
        if C == ' /':
            short_name += '-'
        elif not C == ".'":
            short_name += C.lower()
    sec[short_name] = index

有人可以向我解释我不明白的部分吗,我不喜欢在不知道自己在做什么的情况下写东西。我也不知道for是什么意思。以及如何在没有定义或其他东西的情况下使用 C。如果你能向我解释这一点,那就太好了!

4

3 回答 3

1

在枚举部分,我使代码更加清晰。enumerate允许对 成对进行迭代iteration number, iteration item,因此您不妨单独分配变量。我建议尝试简单的迭代 ( for directionpair in sections:) 和枚举 ( for index,directionpair in enumerate(sections)) 来查看差异。

通过阅读您的描述,您应该使用关键字in来检查 C 是否在字符串“'”中。或“\”,因为任何字符都不可能等于两个字符的字符串。

sec = {} #construct a dictionary
for index, directionpair in enumerate(sections):
    long_name = directionpair[1] #take the second element of the pair
    short_name = ''
    for C in long_name: #for each character in long_name
        if C in ' /': #every time you find a forward slash in long_name, write '-' in short-name instead
            short_name += '-'
        elif C not in "'." : #in short-string, add all lower-case versions of the character if it's not a '.'
            short_name += C.lower()
    sec[short_name] = index

请注意,使用正确的函数可以更轻松地完成此操作,实际上甚至可以使用以下表达式改进re.sub

sec = {} #construct a dictionary
for index, directionpair in enumerate(sections):
    long_name = directionpair[1] #take the second element of the pair
    short_name = long_name.replace('/','-').replace(' ','-').replace("'",'').replace('.','').lower()
    sec[short_name] = index
于 2013-09-01T21:48:17.607 回答
1

for阅读Python中的语句文档后,简短的答案将变得清晰。

  1. indexed遍历sections从 0 开始编号的元素。例如,在第一次迭代中,indexed(0, ("""You are in front...""", "Front..."))

  2. long_name是该部分的第二个元素,即"Front...".

  3. C遍历转换为小写的长名称的字符。C在与比字符长的字符串进行两次比较时,肯定有问题。

于 2013-09-01T21:52:07.677 回答
0

对字符串进行迭代将其分解为 Python 中的字符。所以

for C in 'foo':
    print C

将打印

f
o
o
于 2013-09-01T21:46:46.237 回答