【问题标题】:How to print the items in a list, given through input?如何打印通过输入给出的列表中的项目?
【发布时间】:2021-03-11 18:47:07
【问题描述】:

我有一个保存用户输入的变量。如果用户输入一个列表,例如["oranges","apples","pears"] python 似乎将其作为一个字符串,并打印每个字符,而不是每个单词,如果fruit 只是一个列表,则代码将打印该代码。我如何编写代码来做到这一点?这是我尝试过的...

fruit = input("What is your favourite fruit?")
fruit = list(fruit)
for i in fruit:
  print(i)

【问题讨论】:

  • input always 返回一个字符串。使用输入基本上是一个字符串,您必须以某种方式解析该输入以获得有用的数据结构。通常,您的用户不应该输入像 ["oranges","apples","pears"] 这样的东西,这是源代码。

标签: python string list for-loop input


【解决方案1】:

python 将输入作为一个巨大的字符串,所以它不是一个列表,而是一个看起来像这样的字符串

'["oranges","apples","pears"]'

把它变成一个列表就像

['[', '"', 'o', 'r', 'a', 'n', 'g', 'e', 's', '"', ',', '"', 'a', 'p', 'p', 'l', 'e', 's', '"', ',', '"', 'p', 'e', 'a', 'r', 's', '"', ']']

而不是这个尝试类似这样的东西,它要求你最喜欢的水果,直到你不输入一个水果

Fruits = []
while True:
    temp = input()
    if temp == "":
        break
    else:
        Fruits.append(temp)

然后输出值

for x in Fruits:
    print(x)

【讨论】:

    【解决方案2】:

    你必须用逗号分隔单词。

    fruit = list(fruit.split(","))
    
    
    fruit = input("What is you favourite fruit?")
    fruit = fruit.split(",")
    for i in fruit:
      print(i)
    

    【讨论】:

    • 这将与'["oranges","apples","pears"]'一起工作
    • 这将输出作为水果名称。但是您说的是正确的,将列表作为用户输入传递是不正确的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 2017-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多