从列表+ python中删除整数

时间:2017-05-11 15:17:29

标签: python list

下面是我想要分隔字符串和整数的列表。

此列表给出了正确的结果:

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]

这里有什么问题?

2 个答案:

答案 0 :(得分:2)

问题是:

  1. 当您从列表中删除项目时,您正在遍历列表,
  2. 您的计数器变量x未考虑已删除项目的位置。
  3. 试试这个:

    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
    

    另见:

    (2)(3),{{3}}

答案 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

希望这很清楚,并且有效......