循环遍历列表中列表的第一个元素,但限制它每次只选择第一个项目 Python

问题描述 投票:0回答:0

我试图在列表中循环列表,但是只想选择列表每次迭代的第一项。每次程序运行时随机生成列表。

counter_no = rand_data #the list I'm calling
max_counter_constraint = rand_data[0][1]

while True:
  for some_move in counter_no:
      if max_counter_constraint != counter_no[some_move][0]:
         continue
      elif max_counter_constraint == counter_no[some_move[0]:
         some_loop = False

示例列表如下所示: [[0,5,North] # 第一个元素是移动编号,第二个元素是最大移动约束,第三个是航向(这是唯一一个包含 3 个元素的列表)。然后是:[1, South], [2, South East], [3, North]...等]

现在理论上我的代码应该在移动约束 == 移动数时停止程序。但是它给了我以下错误

TypeError: list indices must be integers or slices, not list
现在我明白我不能调用/类型转换索引,因为 python 只接受整数作为索引,但我似乎无法找到解决这个问题的另一种可能的解决方案。

我已经开始集思广益的解决方案是使用切片来访问列表,例如:

if max_counter_constraint != counter_no[0:100][0]

由于列表被限制为最大长度为 100 个单独的步骤,如果 max_counter_constraint == counter_no,这是否是一个可行的解决方案仍然可以取消?

这也会影响循环吗?

任何建议都会有所帮助。

python turtle-graphics python-turtle
© www.soinside.com 2019 - 2024. All rights reserved.