嗨,我是python的新手,想要在数组中输入.关于数组没有很好地描述python doc.另外我觉得我对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]);
Run Code Online (Sandbox Code Playgroud)
Sri*_*aju 13
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
Run Code Online (Sandbox Code Playgroud)
PS:我已经打了这一切.语法可能是错误的,但方法是正确的.还有一点需要注意的是,raw_input
不做任何类型检查,所以你需要小心......
lig*_*t94 13
如果没有给出数组中元素的数量,您也可以使用列表理解,如:
str_arr = raw_input().split(' ') //will take in a string of numbers separated by a space
arr = [int(num) for num in str_arr]
Run Code Online (Sandbox Code Playgroud)
Siy*_*lav 12
你想要这个 - 输入N然后取N个元素.我在考虑你的输入案例是这样的
5
2 3 6 6 5
Run Code Online (Sandbox Code Playgroud)
在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])
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
171044 次 |
最近记录: |