首页 > 解决方案 > 如何拥有 Python 列表的动态索引

问题描述

我正在寻找一种在 Python 中具有条件动态列表索引的解决方案。

我当前的方法(抽象)在以下情况下不会将索引增加 1 Foo == Bar

# Considered list

list = [
     'itemShiftZero',
     'itemShiftOne'
]


# Basic if-else to define the shift conditionally

if Foo == Bar:
    shift = 1
else:
    shift = 0


# Transfer logic to the list index

item = list[0 + shift]

注意:由于我的代码逻辑,目前没有使两个参数都可变的选项(否则我可以在索引部分之前设置逻辑以仅使用结果变量作为列表索引)

标签: python

解决方案


您的代码在逻辑上很好,除了

  • 您将您的命名list为 as list,从而污染了命名空间。请永远不要将您的列表命名为list. 我已将其重命名为items.
  • 您必须在使用它们之前foo定义变量。bar
  • 尽管这不是您的错误的原因,但作为变量命名约定:变量名称应以小写字母 ( PEP-8 ) 书写,并用下划线分隔
  • 但正如@Booboo 提到的,0作为附加标识,您可以简单地使用item = items[shift].

我的建议

现在说了这么多,如果我是你,我会这样做:

item = items[1 if (foo==bar) else 0]

更正您的代码

# list renamed to items
items = [
     'itemShiftZero',
     'itemShiftOne'
]

# define foo and bar
foo = bar = True

# Basic if-else to define the shift conditionally

if foo == bar:
    shift = 1
else:
    shift = 0


# Transfer logic to the list index

item = items[0 + shift] # list renamed to items
print(item)

输出

itemShiftOne

推荐阅读