如何拥有 Python 列表的动态索引



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

我目前的方法(抽象(,如果Foo == Bar,则不会将索引增加 1:

# 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]

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

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

  • 您将list命名为list,从而污染了命名空间。请不要将您的列表命名为list。我已将其重命名为items.
  • 在使用变量之前,必须定义变量foobar
  • 尽管这不是导致错误的原因,但作为变量命名约定:变量名称应用小写字母 (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

最新更新