【问题标题】:Using a for loop for a dictionary based on user input根据用户输入对字典使用 for 循环
【发布时间】:2021-12-29 18:09:23
【问题描述】:
airport_code = input("Please enter your code")

airport_values = {
    'BCN':'Barcelona',
    'DUB':'Dublin',
    'LIS':'Lisbon',
    'LHR':'London Heathrow',
    'CDG':'Paris',
    'PRG':'Prague',
    'RKV':'Reykjavik',
    'FCO':'Rome'
}

if airport_code in airport_values:
    print('The value is:', airport_values[airport_code])
else:
    print("Sorry that item is not in the list ")

您好,我编写了这段代码来查找用户输入的键是否与存储在字典 airport_values 中的值之一匹配。

当我查看标记方案时,它使用 for 循环代替遍历整个字典并使用计数器检查每个值。

这是用标记方案编写的伪代码。

https://i.stack.imgur.com/huUdQ.png

我想知道的是如何将它应用到 python 而不是我已经完成的方式。

任何帮助将不胜感激。

【问题讨论】:

  • 伪代码并不意味着它是每种语言中最好的解决方案,这是众多语言中的一种
  • 伪代码没有使用字典,它使用的是二维数组。所以它必须搜索数组才能找到匹配项。
  • 在python中还有没有办法做到这一点?
  • 是的。使用元组列表而不是字典。
  • 那么你将如何在 python 中使用计数器,例如在伪代码示例中?我知道这可能不是最好的方法,但这正是老师向我们展示的方式,看看它是如何工作的会很有趣。另外,如果我使用二维数组与我在代码中使用的当前数组相比会有什么不同?

标签: python dictionary for-loop if-statement


【解决方案1】:

并不是说这个伪代码并不意味着这是最好的解决方案。在 python 中,您可以直接签入dict。另外你在 python 中没有 int 索引。


pythonic 方式的迭代可能是这样的

for key, value in airport_values.items():
    if key == airport_code:
        print('The value is:', value)
        break
else:
    print("Sorry that item is not in the list ")

准确的伪代码翻译是

i = 0
airports = list(airport_values.items())
while airports[i][0] != airport_code:
    i += 1
print('The value is:', airports[i][1])

【讨论】:

  • 哦,好吧,所以它必须事先转换成一个列表?
  • @abcdefg 所以可以用int是索引它
  • 你介意我问为什么最后一行的值加一吗?
  • @abcdefg 最后一行是什么?看不到任何增量
  • 第三行是[i][0],最后一行是[i][1]
【解决方案2】:
for i in airport_values:
  if airport_code in airport_values:
    print('The value is:', airport_values[airport_code])
    break

更多关于 python for 循环的信息:https://www.w3schools.com/python/python_for_loops.asp

【讨论】:

    猜你喜欢
    • 2014-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多