在 Python 中获取以空格分隔的整数用户输入

在 Python 中获取用户输入的空格分隔的整数

Taking space-separated integers user input in Python

从用户输入中获取以空格分隔的整数:

  1. 使用该input()函数获取多个以空格分隔的整数。
  2. 使用该str.split()函数将字符串拆分为列表。
  3. 使用int()该类将列表中的每个字符串转换为整数。
主程序
my_list = input('Enter space-separated integers: ').split() list_of_integers = [int(item) for item in my_list] print(list_of_integers)

以空格分隔的整数用户输入

我们使用该input()函数从用户那里获取输入。

输入函数接受一个可选prompt参数并将其写入标准输出而没有尾随换行符

然后该函数从输入中读取该行,将其转换为字符串并返回结果。

请注意input(),即使用户输入整数,该函数也保证返回一个字符串。
主程序
my_list = input('Enter space-separated integers: ').split() list_of_integers = [int(item) for item in my_list] print(list_of_integers)

str.split ()
方法使用定界符将字符串拆分为子字符串列表。

当没有分隔符传递给该str.split()方法时,它会将输入字符串拆分为一个或多个空白字符。
主程序
print('2 4 6 8'.split()) # 👉️ ['2', '4', '6', '8']

最后一步是使用列表理解将列表中的字符串转换为整数。

主程序
my_list = input('Enter space-separated integers: ').split() list_of_integers = [int(item) for item in my_list] print(list_of_integers)
列表推导用于对每个元素执行某些操作或选择满足条件的元素子集。

在每次迭代中,我们将当前列表项传递给int()类以将其转换为整数。

或者,您可以使用该map()功能。

To take space-separated integers from user input:

  1. Use the input() function to take multiple, space-separated integers.
  2. Use the map() function to convert each string to an integer.
  3. Use the list() class to convert the map object to a list.
main.py
list_of_integers = list( map( int, input('Enter space-separated integers: ').split() ) ) print(list_of_integers)

We used the str.split() function to split the string of multiple,
space-separated integers.

The map() function takes
a function and an iterable as arguments and calls the function with each item of
the iterable.

The map function calls the int() class with each value in the list and converts each string to an integer.

The last step is to use the list() class to convert the map object to a
list.