【问题标题】:How to check user input in a list/tuple?如何检查列表/元组中的用户输入?
【发布时间】:2014-11-11 04:33:05
【问题描述】:

基本上我希望我的程序做的是:

new_ch = input("What channel would you like to switch to?")
if new_ch in channels:
      print("You're now on channel,", new_ch,".")
else:
       print("That's not a valid channel.")

无论我做什么,它都会在错误分支上不断打印语句“那不是一个有效的频道”。有没有办法让我的程序使用用户输入搜索我的频道列表/元组?我的频道列表包含变量名 ex。

Ch1 = "Ch1 - Fox News"
Ch2 = "Ch2 - PBS"

Etc.

channels = [Ch1, Ch2, Ch3, ... Ch10]

【问题讨论】:

  • 这对我来说很好用。如果我输入Ch1,那么它将切换到“Ch1 - Fox News”。这不是您所期望的行为吗?
  • 我希望它这样做,但是当我输入 Ch1 时,它会打印出错误的语句。不知道我做错了什么。
  • 你能按顺序发布完整的例子吗?它对我来说很好。在您提供的示例中,任何地方都不应打印False
  • @Bryana 你的 python 版本是什么?频道的格式是什么?
  • 好的,我尽量将代码缩进到我原来的位置,所以一个缩进可能会被关闭。我的 python 版本是 3.4.1 @Kasra

标签: python list tuples in-operator


【解决方案1】:

好的,如果输入是“ch1”并且您希望输出是“Ch1 - Fox News”,那么您的 if 语句不正确。

因为您将“Ch1”与 ['Ch1 - Fox News', 'Ch2 - PBS'] 进行比较:

>>> channels = [Ch1, Ch2]
>>> channels
['Ch1 - Fox News', 'Ch2 - PBS']

所以要纠正这个问题,你需要使用字典,方法如下:

Ch1 = "Ch1 - Fox News"
Ch2 = "Ch2 - PBS"
channels = {"CH1":Ch1,"CH2": Ch2}
new_ch = input("What channel would you like to switch to?")
What channel would you like to switch to?"ch1"
if new_ch.upper() in channels:
    print("You're now on channel,", channels[new_ch.upper()],".")
else:
    print("That's not a valid channel.")


 ("You're now on channel,", 'Ch1 - Fox News', '.')

上层函数只是大小写无关。

更新


随机化:

elif choice == "2":
    ch = random.choice(channels.keys())
    print("You're now on channel", channels[ch],".")

打印频道列表:

elif choice == "1":
    print("\n")
    for item in channels:
        print(channels[item])

【讨论】:

  • 所以我按照您的指示尝试了,但它仍在打印我的虚假陈述。我也无法打印出我的频道列表,也无法使用我的随机选择,所以我不得不制作一个单独的列表,不确定这是否与它有关。
  • 我没有把大写字母放在键中。这非常有效!非常感谢你! @TheCreator232
  • @Bryana :查看更新以解决问题。以供将来参考了解 python 字典的工作原理。
猜你喜欢
  • 2018-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-08
  • 1970-01-01
  • 1970-01-01
  • 2018-04-20
相关资源
最近更新 更多