2016-05-16 105 views
0

我有一個簡單的問題,我無法解決它。我有一個列表;Python在單線程中更改變量的值for循環

[9, 0, 3, 0, 0, 0, 2, 0, 6] 

如果在此列表中的元素是digits,我要加1 counter變量。

digits = [1,2,3,4,5,6,7,8,9] 
lst = [9, 0, 3, 0, 0, 0, 2, 0, 6] 

現在,我與

digits = [1,2,3,4,5,6,7,8,9] 
lst = [9, 0, 3, 0, 0, 0, 2, 0, 6] 
counter = 0 
for x in lst: 
    if x in digits: 
     counter += 1 

做我想寫一個for循環的單行。我試過

t = counter += 1 for x in lst if x in digits 

但是沒有按預期工作。我只是卡住了,我該怎麼做?

+4

'計數器= SUM(中位數×在LST X)' – vaultah

+0

@vaultah這對我來說是一個解決方案,但我想知道怎麼能像'[x for x in x如果x是數字]這樣的單線循環'並且給counter變量加1?我嘗試了'counter + = 1 for x ....',正如我在我的問題中寫的,但沒有奏效。 – GLHF

+1

你可以在'lst:counter + x = digit中做'x' – vaultah

回答

1

可以通過兩種可能的方式做到這一點:

  1. List Comprehensions
counter = len([x for x in lst if x in digits]) 
  • 功能:filter(功能,列表)它提供了一種優雅的方式來過濾列表中的所有元素,爲此函數函數返回True。
  • not_digits = lambda x: x not in digits 
        counter = len(filter(not_digits, lst)) 
    
    1

    我的猜測是,你正試圖在一個列表理解使用Python的語句,而不是一個表達式。這不起作用。我認爲@vaultah在他的評論中提供了一個很好的解決方案。

    如果你堅持明確的分配反擊,也許嘗試reduce

    if 'reduce' not in globals(): 
        from functools import reduce 
    
    counter = 0 
    
    digits = [1,2,3,4,5,6,7,8,9] 
    lst = [9, 0, 3, 0, 0, 0, 2, 0, 6] 
    
    counter = reduce(lambda c, d: c + 1 if d in digits else c, lst, counter)