简体   繁体   English

如何要求n并仅在一行中输入n个数字

[英]How can I ask for n and type the n numbers in only one line

The usual way to input n numbers is to first ask for n and then type n numbers in different lines. 输入n个数字的通常方法是先询问n个,然后在不同的行中键入n个数字。

n = int(input())
for i in range(n):
    x = int(input())

How can I ask for n and type the n numbers in only one line. 如何要求n并仅在一行中输入n个数字。

Something like this: 像这样:

>> 4 1 2 3 4

How can I ask for n and type the n numbers in only one line. 如何要求n并仅在一行中输入n个数字。

You don't need to ask for n if it's obvious from the whitespace-separated input how many integers you have. 如果从空格分隔的输入中可以明显看出您有多少个整数,则无需询问n

However, if the input string format is non-negotiable, you can split via sequence unpacking: 但是,如果输入字符串格式是不可协商的,则可以通过序列解压缩来拆分:

n, *num_list = map(int, input().split())

For example, with input '4 1 2 3 4' , you will have the following result: 例如,输入'4 1 2 3 4' ,您将得到以下结果:

print(n, num_list)

4 [1, 2, 3, 4]

To understand the above logic: 要了解以上逻辑:

  1. input().split() splits a string input by whitespace into a list. input().split()将空格输入的字符串拆分为一个列表。
  2. map(int, X) returns an iterable of int applied to each element in X . map(int, X)返回应用于X每个元素的int迭代
  3. n, *num_list = map(...) iterates the map object and separates into the first and the rest. n, *num_list = map(...)迭代map对象,并分为第一个和其余对象。

More idiomatic would be to calculate n yourself: 比较习惯的做法是自己计算n

num_list = list(map(int, input().split()))
n = len(num_list)

For example, with input '1 2 3 4' , you will have the following result: 例如,输入'1 2 3 4' ,您将得到以下结果:

print(n, num_list)

4 [1, 2, 3, 4]

The only purpose of entering the number of numbers explicitly is to provide a check. 明确输入数字的唯一目的是提供一个检查。 This is possible via an assert statement: 这可以通过一个assert语句来实现:

n, *num_list = map(int, input().split())

assert n == len(num_list), f'Check failed: {n} vs {len(num_list)} provided does not match'
space_separated_numbers = input()
num_list = [int(x) for x in space_separated_numbers.split()]

The trick is to take the whole input as a string at once, and then split it yourself. 诀窍是立即将整个输入作为字符串,然后自己分割。

EDIT: If you are only concerned with getting the first number, just get the first value instead. 编辑:如果您只关心获取第一个数字,则只需获取第一个值即可。

space_separated_numbers = input()
num = space_separated_numbers.split()[0]

Perhaps you can try processing the entire input as a string. 也许您可以尝试将整个输入作为字符串处理。 Then convert them to integers. 然后将它们转换为整数。 In that case, you won't need to specify the value of n too. 在这种情况下,您也不需要指定n的值。

>>> x = [int(y) for y in input().split()]
1 2 3 4
>>> x
[1, 2, 3, 4]

You can then work with the values by iterating through the list. 然后,您可以通过遍历列表来使用这些值。 If you need the value of n, just get the length of the list. 如果需要n的值,则只需获取列表的长度即可。

>>> n = len(x)
>>> n
4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM