Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 迭代时更改列表中的项目_Python 3.x - Fatal编程技术网

Python 3.x 迭代时更改列表中的项目

Python 3.x 迭代时更改列表中的项目,python-3.x,Python 3.x,我正在制作一个需要玩家与怪物战斗的游戏。用户可以告诉玩家移动到哪里,并显示一个棋盘。棋盘只是一个列表,我将其设置为空格,然后当玩家在列表上移动时设置为X 举例说明我的意思: ['','','','X',''] 玩家向左移动 ['','','X','',''] 当玩家到达一个怪物时,会考虑玩家前进的方向,并且棋盘的那一边充满了怪物,所以玩家不能不战斗就跑过去 范例 ['','','monster','X',''] #player moves left #new list after the l

我正在制作一个需要玩家与怪物战斗的游戏。用户可以告诉玩家移动到哪里,并显示一个棋盘。棋盘只是一个列表,我将其设置为空格,然后当玩家在列表上移动时设置为X

举例说明我的意思:

['','','','X','']
玩家向左移动

['','','X','','']
当玩家到达一个怪物时,会考虑玩家前进的方向,并且棋盘的那一边充满了怪物,所以玩家不能不战斗就跑过去

范例

['','','monster','X','']
#player moves left
#new list after the list is filled with monsters
['monster','monster','monster','','']
我想知道的是,当用户让玩家走进怪物时,我将如何填写该列表

我现在的资料如下:

#note that num and my two lists are being predefined in this example. 
#Normally there is other code to determine where the monster
#goes and where the user is.

floor1 = ['','','X','','']
floor1_monsters = ['','','monster','','']
num = 2
user = X


if floor1[num] == user and floor1_monsters[num] == 'monster':
  if move == 'left':
    for i in (0,floor1[num]):
      floor[i] = 'monster'
运行此操作时出现的错误:

TypeError:列表索引必须是整数或片,而不是str

num是分配用于始终保持用户位置的变量

floor1是一个列表,其中包含用户和将充满怪物的列表

用户是“X”

楼层1_怪物是另一个独立于楼层1的列表,用于存放怪物所在的位置

怪物列表和用户列表都有5长,因此num有助于在用户进入怪物也占据的空间时提醒用户

运行代码后,我希望floor1如下所示:

['monster','monster','monster,'','']

如果需要,我会提供更多信息。提前感谢。

如match在评论中所述,
floor1[num]
将获取索引
num
列表中的值。这将是值
X
或值
'
。他的解决办法是:

#note that num and my two lists are being predefined in this example. 
#Normally there is other code to determine where the monster
#goes and where the user is.

floor1 = ['','','X','','']
floor1_monsters = ['','','monster','','']
num = 2
user = "X"
move = "left"


if floor1[num] == user and floor1_monsters[num] == 'monster':
  if move == 'left':
    for i in range(num):
      floor1_monsters[i] = 'monster'

print(floor1_monsters)
如果玩家向左移动,则可以验证是否有效。由于这将填充从索引0到索引X的怪物列表,
monster
重叠

然而,如果你的玩家方向正确,并且你想要一个怪物列表,
[“”,'monster','monster','monster','monster']
,那么这条路线将失败

在这种情况下,您需要从
num
索引到列表末尾运行迭代

  if move == 'right':
    for i in range(num, len(floor1_monsters)):
      floor1_monsters[i] = 'monster'

对于i in(0,floor1[num]):
-
floor1[num]
将是
'
X
或类似-因此
floor[i]
将无效。你是说像“我在范围内(num)”这样的
?@match这不足以填满整个列表吗?谢谢你把我仓促的评论变成了正确的答案!