【问题标题】:Check Python List/Dict based on user input & display from the same index value in another list根据用户输入检查 Python 列表/字典并从另一个列表中的相同索引值显示
【发布时间】:2021-03-04 23:17:59
【问题描述】:

所以我们要求用户输入一个数字并在列表中匹配该数字:

numbers = [1, 2, 3]
num_words = ['One', 'Two', 'Three']
print('Type a number from 1 -3: ')
user = int(input())
if user in numbers:
  print(f"{user} is the digit you typed " + ???)

完成后,我想匹配用户在数字列表中输入的内容,并在下一个列表中打印出相应的索引值。

所以用户输入 1 并检查数字,如果找到,它会打印:一 从 num_words 列表到用户。

我也尝试了字典,但不知道如何根据用户的输入和与 dict 键的匹配向用户显示匹配值:

nums = {1: 'One', 2: 'Two', 3: 'Three'}
print ('Type 1, 2, or 3: ')
user = int(input())

if user in nums.keys():
   print(num.values) #Need it to print the nums.value based on the users input at match to nums.keys
else:
   print('Goodbye!')

但是,我的 Google 搜索没有找到与我正在尝试执行的操作类似的任何内容。我在这里找到了主题(例如:Stackover Flow TpoicStackover Flow topic 2,但这并没有帮助,因为据我所知(以及目前对 Python 的理解)它并没有 100% 符合我想要做的事情。

【问题讨论】:

  • print(num.values)更改为print(nums[user])

标签: python python-3.x list dictionary user-input


【解决方案1】:

对于第一个列表示例,使用.index() 查找第一个列表中数字的索引位置,然后使用该值查找第二个列表中的项目:

if user in numbers:
    location = numbers.index(user)
    print(num_words[location])

对于带有字典的第二个示例,只需使用标准 dict 查找:

if user in nums:
    print(nums[user])

【讨论】:

    【解决方案2】:

    从字典中获取值的语法是dictionary_name[key]。如果找不到密钥,这将引发KeyError,因此您可以使用try/except 而不是提前检查并执行if/else

    nums = {1: 'One', 2: 'Two', 3: 'Three'}
    print ('Type 1, 2, or 3: ')
    user = int(input())
    
    try:
        print(f"{user} is the digit you typed {nums[user]}")
    except KeyError:
       print('Goodbye!')
    

    如果您不希望此代码在无效的整数输入上引发 ValueError,您可以只使用字符串作为字典键:

    nums = {'1': 'One', '2': 'Two', '3': 'Three'}
    print ('Type 1, 2, or 3: ')
    user = input()
    

    【讨论】:

      【解决方案3】:

      来了。您可以向其中添加错误捕获,但这可能是将来的课程:

      numbers = [1, 2, 3]
      num_words = ['One', 'Two', 'Three']
      print('Type a number from 1 -3: ')
      user = int(input())
      if user in numbers:
        print(f"You typed: {num_words[numbers.index(user)]}")
      
      #output:
      Type a number from 1 -3: 
      2
      You typed: Two
      

      【讨论】:

        猜你喜欢
        • 2017-07-29
        • 1970-01-01
        • 1970-01-01
        • 2021-12-31
        • 2020-08-05
        • 2018-04-30
        • 2015-02-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多