【问题标题】:Python input() function to store user input in either list or tuple or dictionaryPython input() 函数将用户输入存储在列表、元组或字典中
【发布时间】:2016-04-28 17:13:12
【问题描述】:
words = input("Enter a word to find its length: ")

for x in words:
    print x, len(x)

我希望这段代码在运行时用于用户输入,以便用户输入可以存储在 word 中,并且可以在运行时的 for 循环中使用。

应该怎么做?

【问题讨论】:

  • 它不是按原样工作吗?
  • 我相信他希望用户能够输入多个单词
  • list = [None]*3 x = True z = 0 while z

标签: python list loops for-loop input


【解决方案1】:
list = [None]*3
x = True

z = 0
while z < 3:
    y = raw_input("Enter a word to find its length: ")
    if(y == "n"):
        x = False;
    else:
        list[z] = y;
        print len(list[z]);
        z +=1 

【讨论】:

    【解决方案2】:

    这有点 Pythonic:

    result = [None] * 3
    for index in range(len(result)):
        y = raw_input("Enter a word to find its length: ")
        if y == "n":
            break
        else:
            result[index] = y
            print len(result[index])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-15
      • 1970-01-01
      • 1970-01-01
      • 2021-04-13
      • 2015-05-28
      • 1970-01-01
      相关资源
      最近更新 更多