Python有人能给我解释一下它的功能和工作原理吗?

2024-04-18 22:44:40 发布

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

我按照一个教程来创建一个文本冒险,我现在创建的部分,仍然没有完成,但有一些我只是不明白。所以,我正在为这些部分创建一个数组。数组包括描述和名称。现在节的名称有一个代码降低它,用-'替换空格,并删除句点和撇号。然后将其放入一个名为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。如果你能给我解释一下,那就太好了!你知道吗


Tags: thenameinfriendyouforindexis
3条回答

在enumerate部分,我使代码稍微清晰了一点。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

在Python中,对字符串进行迭代会将其分解为多个字符。所以呢

for C in 'foo':
    print C

将打印

f
o
o

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

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

  2. long_name是节的第二个元素,即"Front..."

  3. C遍历转换为小写的长名称的字符。在C与比一个字符长的字符串的两个比较中,肯定有什么问题。

相关问题 更多 >