2017-08-13 43 views
1

我有一個分配內:使用枚舉發電機

鑑於可變x列表,寫一個行Python發生器 表達式,返回僅是奇數 或具有在從x個元素甚至(基於零的)索引x。給定的列表可能包含 以外的項目。解決方案必須是一個生成器表達式。

我寫了這方面的工作解決方案

def is_odd_integer(item): 
    if type(item) is int: 
     return item % 2 != 0 
    return False 

def is_even(index): 
    return index % 2 == 0 

def get_odd_integers_or_even_index(list): 
    for index, item in enumerate(list): 
     if is_odd_integer(item) or is_even(index): 
      yield item 


for item in get_odd_integers_or_even_index([1,2,5,6,'sdf', '12',5,4,3,4,4,4,4]): 
    print(item) 

是否使用enumerate一條巨蟒發電機內打敗它的目的是什麼?如果是的話,你將如何實現這一點?

+0

我沒有看到任何生成器表達式。 –

+0

閱讀「發電機表達式」。 – sureshvv

回答

1
[v for i, v in enumerate(x) if ((type(v) is int and v % 2 == 1) or i % 2 == 0)] 

編輯: 編輯後的溶液來匹配coditions See it working at rextester.

+0

另一個條件'i%2 == 0' –

+0

@Andomar如果這被認爲是一個Python生成器?我想不是。如我錯了請糾正我。 – WebQube

+0

它是一個生成器表達式 – sureshvv

0
result = (item for item in x if (isinstance(item, int) and not item%2==0) 
           or x.index(item)%2==0) 

發生器表達式類似於寫作 「元組推導」 和是以下格式:

generator = (item for item in iterable if condition) 

由於,在問題特別要求你寫一個單線程生成器表達式,你可以使用上面的命令行。然而,在條款以書面Python化代碼,我建議你奇數的計算中分離出來lambda函數,例如:

is_odd = lambda x: x%2 == 1 
results = (item for item in x if (isinstance(item, int) and is_odd(item)) 
            or not is_odd(x.index(item)) 
0

你可以使用一個generator expression。既然你需要訪問列表的指數,你可以從一個range表達式開始,並用它來評估的指標,或通過[]運營商訪問列表的項目:

(lst[i] for i in range(0, len(lst)) if (i % 2 == 0) or (isinstance(lst[i], int) and lst[i] % 2 == 1)) 

不管這句法比你的更好儘管如此,嘗試仍然是旁觀者的眼睛。

0

是,enumerator可以內部generator被這裏使用的是樣品與輸入和輸出: -

輸入

x = [1,2,5,6,'sdf', '12',5,4,3,4,4,11,4] 

枚舉和發電機

y = (value for index, value in enumerate(x) if type(value) is int and (value % 2 == 1 or index %2 == 0)) 

輸出

print (list(y)) 
[1, 2, 5, 6, 5, 4, 3, 4, 4, 4] 
+0

'value%2 == 1'他想要奇數 – Nullman

+0

@Nullman謝謝,我的錯誤 –