Python - 创建单独的列表但整数和字符串不起作用
Python - create separate lists but integers and strings not working
信息如下:
我有一个这样的列表
trylist=[9,0,-5,1,-600,'Europe','-9',4,'English',0.7,5.9,'0','-2','-3.7','Python']
希望创建三个列表 - integer、string 和 float
整数列表 将有:9,0,-5,1,-600,4
浮动列表 将有:0.7,5.9
字符串列表 将有:Europe,-9,English,0,-2,-3.7,Python
写了这个程序。输出是整数和标记为字符串的整数。不是我想要的那种。调整它以对浮动做同样的事情。不工作。寻找更好的方法来获得所需的输出。谢谢!
trylist=[9,0,-5,1,-600,'Europe','-9',4,'English',0.7,5.9,'0','-2','Python']
newlistint=[]
newlistonlyint=[]
print(f'Initial list : {trylist}')
for item in trylist:
try:
int_val = int(item)
print(int_val)
except ValueError:
pass
else:
newlistint.append(item) #will print only integers including numbers mentioned as string and digit of float
print(f'newlistint is : {newlistint}')
newlistonlyint.append(int_val)
print(f'newlistonlyint is :{newlistonlyint}')
int() 尝试将其参数转换为 int,如果无法完成则引发 ValueError。虽然 int() 的任何整数参数确实不会引发 ValueError,但像 '9' 这样的非整数参数可以成功转换为整数(在本例中为整数 9),因此不会引发 ValueError.
因此,尝试通过调用 int() 并捕获 ValueErrors 来验证某物是否为整数是行不通的。
您真的应该使用 isinstance() 函数。具体来说,当且仅当 isinstance(item, int) returns 为真时,item 是一个 int。同样,您可以通过将 int 替换为 str 或 float 来检查字符串或浮点数。
trylist = [9,0,-5,1,-600,'Europe','-9',4,'English',0.7,5.9,'0','-2','Python']
int_list = [x for x in trylist if type(x)==int]
float_list = [x for x in trylist if type(x)==float]
str_list = [x for x in trylist if type(x)==str]
您可以阅读有关列表理解的内容here
信息如下: 我有一个这样的列表
trylist=[9,0,-5,1,-600,'Europe','-9',4,'English',0.7,5.9,'0','-2','-3.7','Python']
希望创建三个列表 - integer、string 和 float
整数列表 将有:9,0,-5,1,-600,4
浮动列表 将有:0.7,5.9
字符串列表 将有:Europe,-9,English,0,-2,-3.7,Python
写了这个程序。输出是整数和标记为字符串的整数。不是我想要的那种。调整它以对浮动做同样的事情。不工作。寻找更好的方法来获得所需的输出。谢谢!
trylist=[9,0,-5,1,-600,'Europe','-9',4,'English',0.7,5.9,'0','-2','Python']
newlistint=[]
newlistonlyint=[]
print(f'Initial list : {trylist}')
for item in trylist:
try:
int_val = int(item)
print(int_val)
except ValueError:
pass
else:
newlistint.append(item) #will print only integers including numbers mentioned as string and digit of float
print(f'newlistint is : {newlistint}')
newlistonlyint.append(int_val)
print(f'newlistonlyint is :{newlistonlyint}')
int() 尝试将其参数转换为 int,如果无法完成则引发 ValueError。虽然 int() 的任何整数参数确实不会引发 ValueError,但像 '9' 这样的非整数参数可以成功转换为整数(在本例中为整数 9),因此不会引发 ValueError.
因此,尝试通过调用 int() 并捕获 ValueErrors 来验证某物是否为整数是行不通的。
您真的应该使用 isinstance() 函数。具体来说,当且仅当 isinstance(item, int) returns 为真时,item 是一个 int。同样,您可以通过将 int 替换为 str 或 float 来检查字符串或浮点数。
trylist = [9,0,-5,1,-600,'Europe','-9',4,'English',0.7,5.9,'0','-2','Python']
int_list = [x for x in trylist if type(x)==int]
float_list = [x for x in trylist if type(x)==float]
str_list = [x for x in trylist if type(x)==str]
您可以阅读有关列表理解的内容here