首页 > 解决方案 > 从一组选项中动态查找列表中的 index()

问题描述

def _parse_options(productcode_array):
    if not self._check_productcode_has_options(productcode_array):
        return None
    possible_options = {"UV1", "UV2", "Satin", "Linen", "Unco", "Natural"}
    option_index = productcode_array.index()

的示例值productcode_array

["BC", "1.5x3.5", "100lb", "Linen", "Q100"]

我最初的想法是可能try/except有一个列表理解,但我觉得可能有一种我不知道的更清洁的方式。

我想要实现的是在我的列表productcode_array中获取任何 1possible_options存在的索引位置。我知道总是只有 1 个选项存在。我需要这个的原因是因为产品代码中的索引位置取决于许多因素。

index()使用我的集合的每个值的干净有效的方法是possible_options什么?

标签: pythonpython-3.xlist

解决方案


示例try/except

for x in possible_options:
  try:
    option_index = productcode_array.index(x)
  except ValueError:
    pass

这确实有效,但感觉很脏,所以对更清洁的选择持开放态度。


推荐阅读