【问题标题】:Is there a way to print different list elements depending on input?有没有办法根据输入打印不同的列表元素?
【发布时间】:2022-01-18 17:43:54
【问题描述】:

我有这个 python 代码

color = input("Color? ")
color_list = ["orange", "red", "green", "blue", "pink"]

if color in color_list:
    if color == "orange":
        print("This is orange")
    elif color == "red":
        print("This is red")
else:
  print("Color invalid")

有没有办法在同一个print() 上打印列表的不同元素,这样我就不必为列表中的每种颜色都写一个elif:

对不起,如果你听不懂我的话,我还在学习英语。

【问题讨论】:

  • 你为什么不直接打印color
  • 你已经检查了它是否在列表中,为什么还要检查它是列表中的哪个具体的东西?
  • 这里不需要使用if语句使用简单的f string:print(f'This color is {color}')

标签: python list


【解决方案1】:

如果您只打印在列表中找到的颜色名称,那么您就可以

color = input("Color? ")
color_list = ["orange", "red", "green", "blue", "pink"]

if color in color_list:
    print(f"This is {color}")
else:
    print("Color invalid")

如果您想做其他事情,例如将颜色从英语翻译成芬兰语,您可以使用字典:

color_map = {
    "orange": "oranssi",
    "red": "punainen",
    "green": "vihreä",
    "blue": "sininen",
    "pink": "vaaleanpunainen",
}

color = input("Color? ")

if color in color_map:
    print(f"{color} in Finnish is {color_map[color]}")
else:
    print("Sorry, I don't know what that is in Finnish")

【讨论】:

    【解决方案2】:

    也许你的代码可以像这样缩短

    color = input("Color? ")
    color_list = ["orange", "red", "green", "blue", "pink"]
    
    # check if the color is in the list
    if color in color_list:
        # if there is, it means color is one of the colors from the list
        # so you just have to output it
        print("This is " + color)
    else:
      print("Color invalid")
    

    【讨论】:

    • 问题已经回答,您的回答与问题的正确答案相同
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-26
    • 1970-01-01
    • 2011-07-25
    相关资源
    最近更新 更多