我按照一个教程来创建一个文本冒险,我现在创建的部分,仍然没有完成,但有一些我只是不明白。所以,我正在为这些部分创建一个数组。数组包括描述和名称。现在节的名称有一个代码降低它,用-'替换空格,并删除句点和撇号。然后将其放入一个名为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。如果你能给我解释一下,那就太好了!你知道吗
在enumerate部分,我使代码稍微清晰了一点。
enumerate
允许在成对的iteration number, iteration item
上进行迭代,因此您最好单独分配变量。我建议用直接的迭代(for directionpair in sections:
)和枚举(for index,directionpair in enumerate(sections)
)来进行试验,看看两者的区别。你知道吗通过阅读您的描述,您应该使用关键字
in
来检查C是否在字符串“'”或“\”中,因为任何字符都不能等于两个字符的字符串。你知道吗请注意,使用正确的函数可以更容易地实现这一点,实际上,甚至可以使用
re.sub
改进下面的表达式:在Python中,对字符串进行迭代会将其分解为多个字符。所以呢
将打印
在阅读Python中
for
语句的文档后,简短的答案将变得清晰。你知道吗indexed
遍历从0开始编号的sections
元素。E、 例如,在第一次迭代中,indexed
是(0, ("""You are in front...""", "Front..."))
long_name
是节的第二个元素,即"Front..."
。C
遍历转换为小写的长名称的字符。在C
与比一个字符长的字符串的两个比较中,肯定有什么问题。相关问题 更多 >
编程相关推荐