【问题标题】:Python - converting a series of unknown number of input() entries into a list or an array?Python - 将一系列未知数量的 input() 条目转换为列表或数组?
【发布时间】:2013-09-04 18:54:32
【问题描述】:

I'm taking an intro to python class online 该网站旨在将 input() 数据自动输入到您编写的程序中,以解决各种 Python 逻辑问题。

Please see this page to see how the online class's tool uses input entries

例如类随机输入以下内容:

30
centered
text
is
great
testing
is
great
for
python!
END

显然,我必须将 30 转换为 int。如何将其余部分转换为可用的列表或数组?

width = int(input())
lis = ['centered', 'text', 'is', 'great', 'END']

【问题讨论】:

  • 我不太确定你在问什么。您将元素附加到 name.append(element) 之类的列表中。而且您似乎已经知道如何使用 input() 读取输入。那你有什么问题呢?

标签: python arrays list input


【解决方案1】:

听起来你想循环调用input。这是一种方法:

lst = []
s = input()
while s != 'END':
    lst.append(s)
    s = input()

对于如何设置循环条件还有其他选项,但我认为这是最直接的。如果计算何时停止循环更复杂,另一种设计可能是使循环无条件(使用while True),然后在满足正确条件时使用break

【讨论】:

    【解决方案2】:

    您可以创建一个列表并一个一个地读取每个字符串,并将其添加到列表中:

    width=int(input())
    lis=[]
    tmp=''
    while tmp!='END':
        tmp=input()       #receives a string, in python 3.0+
        lis.append(tmp)
    

    【讨论】:

      【解决方案3】:

      他们为您提供的input() 方法将在调用时返回用户输入的每一行。例如,以下函数通过在整个循环中调用 input 来打印输入的每一行

      for line in range(6):
         print(input())
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-08
        • 2019-01-23
        • 2021-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-24
        相关资源
        最近更新 更多