2017-05-11 105 views
1

下面是我想要分隔字符串和整數的列表。從列表中刪除整數+ python

這份名單給了我正確的結果:

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) 

當我一個元素添加到列表類似下面的問題開始: 添加的元素後,3231 ... 456

>>> list_a = ["Michell",123,"Apple","Food",456,3231,"Another"] 
... 
['Michell', 'Apple', 'Food', 3231, 'Another'] 
[123, 456] 

是什麼這裏的問題?

+0

FYI:我不能編輯其他人的帖子,但'intergers'是標題中的拼寫錯誤! –

回答

2

的問題是:

  1. 您遍歷列表,你從中刪除項目,並
  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)(2)(3)

+0

'list_a.pop(list_a.index(item))'會比'list_a.remove(item)'更簡單,但如果涉及重複的項目,它仍然是錯誤的。要做到這一點,你可能會想要重建一個新的'list'(帶有值保留),然後替換整體,或者反向循環,並使用'enumerate'來獲得精確的刪除索引。 – ShadowRanger

+0

@Nolan你釘了它 – danny

0

@NolanConaway應該是公認的答案。

這就是說,只是爲了告訴你,如果你不希望使用該列表的副本,並使用pop(),你將不得不遍歷您list_a從年底開始,以避免您的x超出範圍。這裏有一個例子:

list_a = ["Michell", 123, "Apple", "Food", 456, 3231, "Another"] 
list_e = [] 

for x, item in reversed(list(enumerate(list_a))): 
    print "x is: ", x 
    print "item is: ", item, type(item) 
    if isinstance(item,int): 
     list_e.append(item) 
     list_a.pop(x) 

print list_a 
print list_e 

將輸出:

x is: 6 
item is: Another <type 'str'> 
x is: 5 
item is: 3231 <type 'int'> 
x is: 4 
item is: 456 <type 'int'> 
x is: 3 
item is: Food <type 'str'> 
x is: 2 
item is: Apple <type 'str'> 
x is: 1 
item is: 123 <type 'int'> 
x is: 0 
item is: Michell <type 'str'> 
['Michell', 'Apple', 'Food', 'Another'] 
[3231, 456, 123] 
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 

希望這是明確的,它的作品....