【问题标题】:Find keys of dictionary that sum to 6查找总和为 6 的字典键
【发布时间】:2022-11-18 08:05:18
【问题描述】:

我在访问字典中的多个值时遇到问题。假设我有这本字典:

{'1': 0, '2': 1, '3': 2, '4': 3, '5': 4, '6': 5}

我想找到两个总和为 6 的键并显示它们的值。这里,键 4 和 2 加起来是 6,所以 2 的值是 3 和 1。

我从哪说起呢?这是我到目前为止的代码:

for key in dico:
        if sum(key + key) == 6:
                print(f"Numbers @ {key:dico} have a sum of 6")

【问题讨论】:

  • 如果以下任何答案解决了您的问题,那么您应该将最能帮助您的答案标记为正确(打勾)。

标签: python dictionary key


【解决方案1】:

不需要额外的循环(或 itertools),它们只会减慢你的程序。您已经知道另一个索引需要是什么(因为您可以从 6 中减去索引),所以只需检查该索引是否存在:

dct = {'1': 0, '2': 1, '3': 2, '4': 3, '5': 4, '6': 5}

for i, key in enumerate(dct):
    if i + 2 > len(dct)/2:
        break
    
    matchIndex = str(6 - int(key))
    if dct.get(matchIndex) is not None:
        print(f'Keys {key} and {matchIndex} have values {dct[key]} and {dct[matchIndex]}')

这种方法具有 O(n/2) 时间复杂度,而另一个答案具有 O(n^2) 时间复杂度。

当我使用 timeit 测试此方法时,运行此答案一百万次需要 1.72 秒,但 itertools 答案需要 5.83 秒。

【讨论】:

  • @IgnatiusReilly 是的,我已经更新了我的答案。尽管在这种情况下,这种方法更快。
  • @IgnatiusReilly 我已经更新了我的答案以包括我通过timeit 得到的确切时间。他们表明这种方法是最快的。
  • 在每种情况下,它将显示两次值,
  • @assume_irrational_is_rational 它打印键和值。如果需要,您可以只打印密钥。这仅取决于print()电话
  • @assume_irrational_is_rational 我已经更新了我的答案以解决您指出的问题。现在它只会遍历一半的键
【解决方案2】:

您需要将每个字典键与其余键进行比较。您可以为此使用itertools

正如您提到的,您想打印字典中每个键的 value,它会是这样的:

import itertools

dico = {'1': 0, '2': 1, '3': 2, '4': 3, '5': 4, '6': 5}

for a, b in itertools.combinations(dico.keys(), 2):
    if int(a) + int(b) == 6:
        print(f"{dico[a]} - {dico[b]}")

【讨论】:

  • 如果在很多键上完成,这将非常耗时。
【解决方案3】:

你需要两个循环。

另外,请记住,该问题的答案不止一个

a = {'1': 0, '2': 1, '3': 2, '4': 3, '5': 4, '6': 5}

results = list()

for key_1 in a.keys():
  for key_2 in a.keys():
    if key_1 != key_2:
      if a[key_1] + a[key_2] == 6:
        if a[key_1] < a[key_2]:
          results.append((key_1, key_2))

print(results)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-05
    相关资源
    最近更新 更多