Python,如何遍历整个列表

时间:2017-09-30 09:34:36

标签: python for-loop continue

我正在创建一个文本冒险游戏,并且在检查对象而不是大量的if语句时

例如

- 如果列表中的单词和location = room则打印描述,

我以为我会遍历一个列表并且只有一个If语句如下所示。

如果位置= 1,我可以输入门或垫并获取说明。 但如果位置= 2,第二门描述就不会出现。

如何让代码遍历整个列表并在位置2打印门的描述?谢谢你的帮助。

list_of_objects =[
    "door","A sturdy door that is firmly locked.",1,
    "door","A test door. Why do I never appear?",2,
    "mat","Its one of those brown bristly door mats.",1]
location = 1
word = ""

def print_description():
    for x in list_of_objects:
        if x == word and location == list_of_objects[list_of_objects.index(word)+2]:
            print(list_of_objects[list_of_objects.index(word)+1])
            return
    print("Sorry, what was that ?  ")

while word != "x":
    word = input("Type door or mat  ")
    print_description()

2 个答案:

答案 0 :(得分:1)

不是一个接一个地创建对象属性的平面列表,而是应该让每个列表成员完全描述该对象。例如,您可以使用元组填充列表:

list_of_objects = [
    ("door", "A sturdy door that is firmly locked.", 1),
    ("door", "A test door. Why do I never appear?", 2),
    ("mat", "Its one of those brown bristly door mats.", 1)
]

然后你可以使用以下方法检查它:

def print_description(user_word, user_location):
    for object_type, description, location in list_of_objects:
        if object_type == user_word and location == user_location:
            print(description)

另一种选择是使用dicts而不是元组作为列表成员。这首先是更多的输入,但它可以让以后更容易添加更多属性,以及包含可选属性。

list_of_objects = [
    { "type": "door",
      "description": "A sturdy door that is firmly locked.",
      "location": 1 },
    ...
]

答案 1 :(得分:0)

执行此操作的最佳方法是使用其键为单词,位置对(元组)的字典:

dict_of_objects = {
    ("door", 1): "A sturdy door that is firmly locked.",
    ("door", 2): "A test door. Why do I never appear?",
    ("mat",  1): "Its one of those brown bristly door mats."
}

然后您只需要:

def print_description():
    key = word, location
    if key in dict_of_objects:
        print(dict_of_objects[key])
    else:
        print("Sorry, what was that ?  ")

这种方式不需要迭代。