gpt4 book ai didi

python-2.7 - 如何在python中获取特定数量的输入

转载 作者:行者123 更新时间:2023-12-04 17:56:23 25 4
gpt4 key购买 nike

如何在 python 中获取特定数量的输入。说,如果我只想在列表中插入 5 个元素,那么我该怎么做?
我试图做到这一点,但无法弄清楚如何。

在第一行中,我想取一个整数,它将是列表的大小。
第二行将包含 5 个由空格分隔的元素,如下所示:

5

1 2 3 4 5

提前致谢。

最佳答案

输入:-

5

1 2 3 4 5

然后,使用以下代码:
n = int(input())    # Number of elements

List = list ( map ( int, input().split(" ") ) )

将空格分隔的输入作为整数列表。这里不需要元素计数。
你可以通过 获取List的大小len(列表) .
这里 列表是用于生成列表的关键字。

或者您可以使用替代方法:
n = int(input())    # Number of elements

List = [ int(elem) for elem in input().split(" ") ]

如果您希望将其作为字符串列表,请使用:
List = list( input().split(" ") )

或者
s = input()   # default input is string by using input() function in python 2.7+

List = list( s.split(" ") )

或者
List = [ elem for elem in input().split(" ")  ]

使用循环在新行中接收输入时需要元素计数,然后
Let the Input be like :

5

1

2

3

4

5

修改后的代码将是:-
n = int(input())

List = [ ] #declare an Empty list

for i in range(n):

elem = int(input())

List.append ( elem )

对于早期版本的 python,使用 raw_input ( ) 而不是 input ( ),后者接收默认输入为字符串。

关于python-2.7 - 如何在python中获取特定数量的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40234584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com