python - 如何拥有 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]
注意:由于我的代码逻辑,目前没有使两个参数都可变的选项(否则我可以在索引部分之前设置逻辑以仅使用结果变量作为列表索引)
解决方案
您的代码在逻辑上很好,除了:
- 您将您的命名
list
为 aslist
,从而污染了命名空间。请永远不要将您的列表命名为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
推荐阅读
- angular - Angular 中的 Rxjs 可观察延迟流单元测试
- haskell - 索引文件夹如何运作?
- python - OSX 上的 tkinter:打开新窗口而不是选项卡
- php - 如何在 PHP 类中添加标题 H2
- css - Django 管理员徽标未加载
- html - Css Grid - 顶行限制高度
- android - Httpconnection 无法正确打开链接
- python - 通过在 pandas 的另一列中拆分字符串来创建新的数据框列
- python - Python - BeautifulSoup 从多个选项中提取价值
- ruby-on-rails - 捆绑包被锁定到 heroku (3.99.3)