python如何手动输入数组_如何在数组+ PYTHON中进行输入?

这篇博客适合Python初学者,介绍了如何在Python中读取键盘输入并将其存储到数组(列表)中。文章通过对比C语言的代码示例,展示了Python中使用`raw_input()`(在Python 3中为`input()`)读取用户输入,并通过列表推导式将输入的数字转换成整数列表的过程。此外,还提供了带有提示的完整代码示例,帮助用户理解如何接受用户输入的元素数量和数组元素。
摘要由CSDN通过智能技术生成

本问题已经有最佳答案,请猛点这里访问。

我是Python的新手,想将键盘输入读取到数组中。 python doc不能很好地描述数组。 我也认为我对Python的for循环有些h。

我给我想要在python中的C代码片段:

C代码:

1

2

3

4

5

6

7

8int 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]);

如果未给出数组中元素的数量,则可以选择使用列表推导,例如:

1

2str_arr = raw_input().split(' ') //will take in a string of numbers separated by a space

arr = [int(num) for num in str_arr]

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.

因此,您的代码基本上将如下所示。

1

2

3

4

5

6

7num_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不执行任何类型检查,因此您需要小心...

你能只解释第一行吗

@Srikar:了解你会...

什么第一行? 我已在答案中添加了更多信息。 你最不明白的是什么?

我也可以这样写:num_array = []而不是num_array = list()我不知道list()方法,这就是为什么要问它会做什么吗?

一样的! 你可以用任何一种方式写...

尽管被接受,但这不能回答上面的问题。 OP不想每次都打印" num:"。 @ light94在下面给出了正确的(且简短的)答案。

您想要这个-输入N,然后接受N个元素。我认为您的输入用例就是这样

1

25

2 3 6 6 5

在python 3.x中具有这种方式(对于python 2.x,如果input(),请使用raw_input()代替)

Python 3

1

2

3n = 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

1

2

3n = 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])

1

2

3

4

5

6data = []

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

2

3

4

5arr = []

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值