我试图做一些培训代码,该代码是将数据类型分开。
我做了一个清单,并用一些数字,字母和浮点数填充
我想要lstInt
中的整数,lstflt
中的浮点数,lstsrt
中的字符串
>>> lst=[1,'a',2,'b',3,'c',4.5,9.9]
>>> lstInt=[]
>>> lstflt=[]
>>> lststr=[]
>>> x=0
>>> for item in lst:
... if isinstance(i, int):
... lstInt.append(i)
... lst.pop(x)
... if isinstance(i, str):
... lststr.append(i)
... lst.pop(x)
... if isinstance(i, float):
... lstflt.append(i)
... lst.pop(x)
... x=x+1
...
1
2
3
4.5
>>> lst
['a', 'b', 'c', 9.9]
>>> lstInt
[]
>>> lstflt
[]
>>> lststr
[]
>>>
答案 0 :(得分:1)
我相信第一个错误是滥用for循环变量。 您已经将“ item”定义为for循环变量,但是在isinstance和append中,您正在使用“ i”。
另外,当您从列表中弹出元素时,您正在更改位置,这会扰乱循环。 for循环以元素0(第一个元素)开始,在您的代码中为数字“ 1”,当程序结束第一次迭代时,它现在将使用元素1(第二个元素),但是由于它弹出了第一个元素,现在第一个元素是字母“ a”,第二个元素是数字“ 2”,这会使程序在每次迭代时都忽略该元素。
我认为您想要的代码是这样的:
>>> for item in lst:
... if isinstance(item, int):
... lstInt.append(item)
... if isinstance(item, str):
... lststr.append(item)
... if isinstance(item, float):
... lstflt.append(item)
答案 1 :(得分:0)
例如
for item in lst:
if isinstance(i, int):
lstInt.append(i)
lst.pop(x)
i
不存在。我认为您的意思是使用item
此外,通过使用pop(x)
,您将通过 index 从列表中删除项目,这意味着如果列表变小,则删除该项目后所有项目的索引减少了,因为有更少的地方可以填充物品。因此,尽管原始列表中的[1,'a',2,'b',3,'c',4.5,9.9]
'b'
在索引3中,但是如果您删除了1 and 'a'
,则该列表现在将是[2,'b',3,'c',4.5,9.9]
,而'b'
将在索引中1,虽然变量x仍会尝试从索引3中删除'b'
,所以pop(3)
将不再删除'b'
,它将删除'c'
。
如果您要编写较长的程序,我不建议您使用python解释器(可以输入命令并自动编译并给出答案的东西,每行以>>>
开头)(我们建议您编写脚本然后执行它们(有时),或者现在使用在线编译器。