从选项集中的列表中动态查找 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其中任何 1 个possible_options存在的位置。我知道永远只有 1 个选项存在。我需要这样做的原因是产品代码中的索引位置取决于许多因素。

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

>>> next(i for i, code in enumerate(productcode_array) if code in possible_options)
3

>>> productcode_array.index(possible_options.intersection(productcode_array).pop())
3

带有try/except的示例:

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

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

您可以使用set.intersection然后分配给option_index(假设只有一个通用值,如注释中所述(:

例如:

possible_options = {"UV1", "UV2", "Satin", "Linen", "Unco", "Natural"}
productcode_array = ["BC", "1.5x3.5", "100lb", "Linen", "Q100"]
for v in possible_options.intersection(productcode_array):
option_index = productcode_array.index(v)
print(option_index)

指纹:

3