【问题标题】:how to read array elements from user in python如何在python中从用户读取数组元素
【发布时间】:2015-03-11 13:56:44
【问题描述】:

我正在尝试将数组元素读取为

4 #no. of elements to be read in array
1 2 3 4 

我通过参考其他答案尝试了什么

def main():

    n=int(input("how many number you want to enter:"))
    l=[]
    for i in range(n):
        l.append(int(input()))

如果我提供输入,这很好用

4 #no. of elements to be read
1
2
3
4

但如果我尝试给予喜欢

4 #no. of element to be read

1 2 3 4

我得到错误:

ValueError: invalid literal for int() with base 10: '1 2 3 4'

请帮帮我

【问题讨论】:

  • 我认为您的意思是当您输入诸如“1 2 3 4”之类的字符串作为输入时,会引发错误。这是因为 Python 无法将其中包含非 int 字符的字符串转换为 int。您需要拆分文本 (.split()) 才能使用并使用结果数组。

标签: python arrays


【解决方案1】:

由于 Python 中没有输入分隔符,您应该使用 split 并拆分您从用户那里收到的输入:

lst = your_input.split()

【讨论】:

  • 此外,这使得 for 循环变得多余 - 但最好向用户指定数字应由空格分隔。
【解决方案2】:

你的第一种方法没问题,第二种方法使用这个:

n=int(input("how many number you want to enter:"))
l=map(int, input().split())[:n] # l is now a list of at most n integers

这将map 函数int 在用户输入(在您的示例中为1234)的拆分部分(split 给出)。

它还使用切片(map 之后的[:n])进行切片,以防用户放入更多整数。

【讨论】:

    【解决方案3】:

    input() 函数返回用户输入的字符串。 int() 函数期望将数字作为字符串转换为相应的数字值。所以int('3') 会返回 3。但是当你输入像1 2 3 4 这样的字符串时,函数int() 不知道如何转换它。

    你可以按照你的第一个例子:

        n = int(input('How many do you want to read?'))
        alist = [] 
    
        for i in range(n):
            x = int(input('-->'))
            alist.append(x)
    

    以上要求您一次只输入一个数字。

    另一种方法是拆分字符串。

        x = input('Enter a bunch of numbers separated by a space:')
        alist = [int(i) for i in x.split()]
    

    split() 方法以字符串形式返回数字列表,不包括空格

    【讨论】:

      【解决方案4】:
      n = input("how many number you want to enter :")
      
      l=readerinput.split(" ")
      

      【讨论】:

        猜你喜欢
        • 2019-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-19
        • 2019-12-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多