下面是我想要分隔字符串和整数的列表。
此列表给出了正确的结果:
list_a = ["Michell",123,"Apple","Food",456,"Another"]
list_e = []
x = 0
for item in list_a:
print("x is: ", x)
print("item is: ", item)
if isinstance(item,int):
list_e.append(item)
list_a.pop(x)
x+=1
print(list_a)
print(list_e)
当我将一个元素添加到列表中时,问题就开始了: 在456 ...
之后添加了元素3231>>> list_a = ["Michell",123,"Apple","Food",456,3231,"Another"]
...
['Michell', 'Apple', 'Food', 3231, 'Another']
[123, 456]
这里有什么问题?
答案 0 :(得分:2)
问题是:
x
未考虑已删除项目的位置。 试试这个:
list_a = ["Michell",123,"Apple","Food",456,3231,"Another"]
list_e = []
x = 0
for item in list_a[:]:
print "x is: ", x
print "item is: ", item, type(item)
if isinstance(item,int):
list_e.append(item)
list_a.pop(list_a.index(item))
x+=1
print list_a
print list_e
另见:
答案 1 :(得分:0)
list_a = ["Michell",123,"Apple","Food",456,3231,"Another"]
numlist=[] #number list
strlist=[] #string list
for i in list_a:
if((type(i))== int): #to find the data type
numlist.append(i)
else:
strlist.append(i)
print numlist
print strlist
希望这很清楚,并且有效......