打印时将位置值附加到列表

时间:2015-12-03 01:15:20

标签: python python-3.x

所以我有一个冒险游戏,我创建了一个位置列表

rooms = [ "You are in the garden. Darkness everywhere.",
          "You are in the bathroom. You sound some noise.",
          "You are in the hall. You almost fall. Stairs east",
          "You are in the kitchen. You can hear voices.",
          "You are in the upstairs hallway. It's quiet. Stairs North.",
          "You are in your room. You're safe." ]

对于每一行,如果它执行我希望它打印让我们说

Location 0
You are in the garden. Darkness everywhere.

我很困惑如何去做。我知道如何让它说出像

这样的东西
Location 0 You are in the garden. Darkness everywhere.

但这不是必需的。

2 个答案:

答案 0 :(得分:1)

使用enumerate功能。

for i,description in enumerate(rooms):
    print(i, description)

答案 1 :(得分:0)

对于您想要格式的每一行:Location 0 You are in the garden. Darkness everywhere.,该数字是room列表中字符串的索引。

做一个这样的循环:

for i in range(len(rooms)):
    print('Location %d %s' % (i, rooms[i]))

将为列表中的所有字符串提供所需的输出。

在该代码段中,%d表示格式化的数字变量,在这种情况下是位置的编号,而%s表示要打印的字符串,是该位置的字符串。列表。