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

2024-05-15 15:29:00 发布

您现在位置: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]

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


Tags: theto方法列表ifshiftfoobar
1条回答
网友
1楼 · 发布于 2024-05-15 15:29:00

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

  • 您将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

相关问题 更多 >