如何在PYTHON中将输入存储到数组中?

15

我是Python的新手,想将键盘输入读入数组中。Python文档对数组的描述不太清楚。同时,我认为在Python中使用for循环时遇到了一些问题。

我将提供一个我想要用Python实现的C代码片段:

C代码:

int i;

printf("Enter how many elements you want: ");
scanf("%d", &n);

printf("Enter the numbers in the array: ");
for (i = 0; i < n; i++)
    scanf("%d", &arr[i]);
5个回答

23

你需要这个-输入N,然后使用N个元素。我假设您的输入情况就像这样。

5
2 3 6 6 5
在Python 3.x中,可以这样写(对于Python 2.x,请使用raw_input()代替input())。
n = int(input())
arr = input()   # takes the whole line of n numbers
l = list(map(int,arr.split(' '))) # split those numbers with space( becomes ['2','3','6','6','5']) and then map every element into int (becomes [2,3,6,6,5])

Python 2

->

Python 2

n = int(raw_input())
arr = raw_input()   # takes the whole line of n numbers
l = list(map(int,arr.split(' '))) # split those numbers with space( becomes ['2','3','6','6','5']) and then map every element into int (becomes [2,3,6,6,5])

17

raw_input 是你的助手。根据文档 -

如果 prompt 参数存在,则将其写入标准输出,而不带有尾随的换行符。然后函数从输入中读取一行,将其转换为字符串(删除尾随的换行符),并返回该字符串。当读到 EOF 时,会引发 EOFError 异常。

所以你的代码基本上看起来像这样:

num_array = list()
num = raw_input("Enter how many elements you want:")
print 'Enter numbers in array: '
for i in range(int(num)):
    n = raw_input("num :")
    num_array.append(int(n))
print 'ARRAY: ',num_array

补充说明:我所有的输入都是手打的。语法可能有误,但方法是正确的。另外需要注意的一点是,raw_input 不会进行任何类型检查,因此您需要小心处理...


请解释一下第一行。 - user1000368
第一行是什么?我已经在我的回答中添加了更多信息。你到底不明白什么? - Srikar Appalaraju
1
我也可以这样写:num_array=[] 而不是 num_array = list() 我不知道 list() 方法,所以想知道它会做什么? - user1000368
无论哪种方式都可以... - Srikar Appalaraju
虽然被接受了,但这并没有回答上面的问题。OP不想每次都打印“num:”。@light94在下面给出了一个正确(且更短)的答案。 - Rohit Rawat

15
如果数组中元素的数量未知,您可以使用列表推导式,例如:
str_arr = raw_input().split(' ') //will take in a string of numbers separated by a space
arr = [int(num) for num in str_arr]

4
data = []
n = int(raw_input('Enter how many elements you want: '))
for i in range(0, n):
    x = raw_input('Enter the numbers into the array: ')
    data.append(x)
print(data)

现在这个程序没有进行任何错误检查,它将数据保存为字符串格式。

1
谢谢Taylor,不幸的是,由于我的余额不足,我无法为您的答案点赞 :( - user1000368

2
arr = []
elem = int(raw_input("insert how many elements you want:"))
for i in range(0, elem):
    arr.append(int(raw_input("Enter next no :")))
print arr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接