在一行中询问python中的整数列表 [英] Ask a list of integer in python in one line
问题描述
def entree_liste():
liste_entier = []
liste_nombre = int(input("Enter list of number separate by space :"))
for chiffre in range(liste_nombre):
liste_entier.append(chiffre)
print(liste_entier)
和我的错误
liste_nombre = int(input("Enter list of number separate by space :"))
ValueError: invalid literal for int() with base 10: '22 33 44 55'
基本上,我要向用户提供一个int列表.如果我执行liste_entier = list(liste_nombre)
,它们会将空间视为整数,并且我不想在列表中仅包含整数.
Basically, I am asking the user for a list of int. If I do liste_entier = list(liste_nombre)
they count space as an integer and I don't want to have space in my list only the integer.
推荐答案
函数int()
会将单个值转换为整数.但是您有一个巨大的字符串,其中嵌入了许多整数值.要解决此问题,请先将巨型字符串拆分为较小字符串的集合(在本例中为列表),每个较小的字符串仅包含一个整数,然后分别转换每个字符串.
The function int()
will convert a single value to integer. But you have one giant string with many integer values embedded in it. To solve this problem, first split the giant string into a collection (in this case, a list) of smaller strings, each containing only one integer and then convert each of those strings separately.
要执行拆分操作,可以使用Python字符串方法.split().那将返回一个字符串列表.然后可以将这些字符串中的每个字符串转换为整数:
To perform the splitting operation, you can use the Python string method .split(). That will return a list of strings. Each of those strings can then be converted to integer:
# get list as string
list_nombre = input("Enter list of numbers separated by space:")
# create list of smaller strings, each with one integer-as-string
list_of_int_strings = list_nombre.split(' ')
# convert list of strings to list of integers
list_of_ints = []
for int_string in list_of_int_strings:
list_of_ints.append(int(int_string)
但是,在Python中,我们会更简洁地编写:
However, in Python we would more concisely write:
list_nombre = input("Enter list of numbers separated by space:")
list_of_ints = ([int(s) for s in list_nombre.split(' ')])
这篇关于在一行中询问python中的整数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!