2015-06-01 119 views
1

這是我的功能:當應用於功能跳過一個條目,我不知道爲什麼

def repeat(x,Y): 
    A = list(str(x)) #makes a list, A, of each digit: 101 becomes ['1','0','1'] 
    A = map(int,A) #converts each value of the new list to integers 

    for i in range(0,10): 
     b = A.count(i) #counts how many times each digit is present 
     if b>1:   #if there is repetition 
      Y.remove(x) 

這似乎在閒置單號運行時,要被罰款,但是一個使用for循環的列表,該函數會丟失一個值。

B = [] 
for i in range(100,1000): #needs to be a 3 digit number (100 until 999) 
    if i%17 == 0: 
     B.append(i)   #creates list of factors of 17 
for j in B:     #removes any values that have digits that occur more than once 
    repeat(j,B) 

這將返回一個包含數字663的列表。當函數在新列表中重新運行時,該值將被刪除。此外,當它應用於不同的列表時,3位數字以13爲因子,同樣發生,一個值與重複數字。

這不是一個很大的不便,只是一個非常討厭的問題。

+0

你爲什麼不試試'set()',你有什麼問題?預期的投入和產出? – ZdaR

+0

您在修改'B'的同時迭代它,這勢必造成麻煩。 – interjay

+0

問題是,當函數被應用時,使用for循環,到值列表中,應該被刪除的一個值仍然存在。我相對較新的python,我將如何實現設置功能? – twallien

回答

1

255在272被刪除之前,272被跳過。同樣,663在被刪除之前被直接跳過爲646。

我懷疑它可以做就地修改陣列@interjay說。

ETA:隨着調試語句放了進去,可以看到的是被刪除的號碼後,立即來到數字,將跳過這些:

def repeat(x,Y): 
    A = list(str(x)) #makes a list, A, of each digit: 101 becomes ['1','0','1'] 
    A = map(int,A) #converts each value of the new list to integers 
    print 'Proceessing', x 
    for i in range(0,10): 
     b = A.count(i) #counts how many times each digit is present 
     if b>1:   #if there is repetition 
      print 'Removed', x 
      Y.remove(x) 


B = [] 
for i in range(100,1000): #needs to be a 3 digit number (100 until 999) 
    if i%17 == 0: 
     B.append(i)   #creates list of factors of 17 
print B 

for j in B:     #removes any values that have digits that occur more than once 
    repeat(j,B) 

print B 
0

由於意見建議,不修改的列表,而迭代它。另外,Python提供Counter來計算迭代次數,所以你不需要自己實現它。最後,由於您反覆過濾了一個迭代,因此使用filter是明智的。

import collections 
def norepeats(x): 
    counts = collections.Counter(str(x)) 
    return not any(ci > 1 for ci in counts.values()) 

threedigit = range(100,1000) 
b1 = filter(lambda x: 0==x%17, threedigit) 
b2 = filter(norepeats, b1) 

print b2 #the result you expected 
相關問題