2017-08-10 40 views
1

我試圖劃分列表的每個元素,以查看列表中的數字是否返回偶數。我想要的是將list_accepted_ant中的偶數值附加到set_accepted_list。目前,當我打印該值時,所有值都附加到set_accepted_list。任何幫助將不勝感激。如何將整個列表中的每個元素除以常量

def DoIOpenTheDoor(list_ant_id): 
    list_accepted_ant = []      
    set_accepted_list = set() 
    set_forbidden_list = set() 
    set_list_ant_id = set(list_ant_id) 
    if len(list_accepted_ant) < num_accepted: 
     if len(list_ant_id) > 0: 
      list_accepted_ant.extend(list_ant_id[0:min(len(list_ant_id)) 
       if (all(x % 2 == 0 for x in list_accepted_ant)): 
        list_accepted_ant.append(list_accepted_ant) 
    set_accepted_list = set(list_accepted_ant) 
    print "the set of even accepted ant-",(set_accepted_list) 
    print "the list of all ants-",(list_ant_id)  
    set_forbidden_list = set_list_ant_id-set_accepted_list 
    return set_accepted_list,set_list_ant_id,set_forbidden_list 

這是我的輸出,當我運行代碼:

list_ant_id = [1082, 1091, 1055, 1057, 971, 977, 728, 740]

set_accepted_list = set([1057, 1091, 740, 971, 977, 728, 1082, 1055])

我預計set_accepted_list = set([740,728,1082])

基本上我想要的是保持偶數值從list_ant_id到set_accepted_list。

+2

您在'if len(list_ant_id)> 0:' – lmiguelvargasf

+1

'list_accepted_ant == 0'是一個布爾值,並且您正在嘗試爲'x in'做一個布爾值,因此有一個縮進錯誤您的錯誤 – depperm

回答

1

的問題是,您要比較的迭代x/2 for x in list_accepted_ant與多家0,所以更改:

([x/2 for x in list_accepted_ant ==0]): #for even number ants 

all(x % 2 == 0 for x in list_accepted_ant)) 

前行基本上是說爲list_accepted_ant每個元素檢查他們都是平均的。

+0

錯誤已解決,但我無法獲得所需的結果。 – mudaliyar

+0

@imigyelvargasf。我編輯了這個問題並提供了輸入和預期輸出。 – mudaliyar

相關問題