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