如何接受数组+PYTHON中的输入?

2024-06-02 04:30:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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]);

Tags: the代码文档youfor数组elementsmany
3条回答

你想要这个-输入N,然后取N个元素。我认为你的输入大小写是这样的

5
2 3 6 6 5

在python 3.x中这样做(对于python 2.x,如果input(),则使用raw_input()

Python3

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])

Python2

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])

raw_input是你的助手。从文件中-

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

所以你的代码基本上是这样的。

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不做任何类型检查,因此需要小心。。。

如果未给出数组中元素的数目,则可以使用列表理解,如:

str_arr = raw_input().split(' ') //will take in a string of numbers separated by a space
arr = [int(num) for num in str_arr]

相关问题 更多 >