0

我正在构建的脚本的一部分要求我将用户输入映射到列表(可能的输入),然后将其关联到字典中的键(结果)。我已经设法获得结果,但我想知道有没有更好的方法可以解决这个问题?

user_input = "bought"
output = None

input_mapping = {"buy": ["bought", "buys", "purchased"],
                 "sell": ["sold", "sells", "sale"]}

for key, values in input_mapping.items():
    if user_input in values:
        output = key

print(output)

输入输出:

user_input = "sale"
>>> sell

user_input = "bought"
>>> buy

非常感谢!

4

3 回答 3

2

在这种情况下,保留反向字典将产生最佳性能。搜索字典非常好,而您的方法需要搜索整个数据。

我会构建一个简单的反向字典并使用它:

reversed_dictionary = {item[0]: item[1] for sublist in [[(v,k) for v in input_mapping[k]] for k in input_mapping.keys()] for item in sublist}
于 2020-09-23T10:18:53.023 回答
1

让多个键指向同一个值似乎更多余,但从性能方面来看,在字典中查找键O(1)比在列表中查找值更有效O(N)

input_mapping = {
  "bought": "buy",
  "buys": "buy",
  "purchased": "buy",
  "sold": "sell",
  "sells": "sell",
  "sale": "sell"
}

user_input = "bought"
output = input_mapping[user_input]
print(output)

代码输出:

buy
于 2020-09-23T10:19:02.687 回答
1

您应该反转映射,从输出 -> [输入] 到输入 -> 输出映射:

mapping = {
  "bought": "buy", "buys": "buy", "purchased": "buy", "sold": "sell", "sells": "sell",
  "sale": "sell"}
output = mapping[input]

那会更快,更直观。如果数据变得非常大,我更喜欢您的解决方案。这是一个权衡。

于 2020-09-23T10:22:14.067 回答