簡體   English   中英

Python - 查找混合數組中每個值的出現(整數,列表)

[英]Python - Finding each occurrence of a value in a mixed array (integers, lists)

我有一個數組: x = [ [1, 2], 1, 1, [2, 1, [1, 2]] ]其中我想計算數字1每次出現次數,並將該數字存儲在變量中one_counter x.count(1)僅返回2次出現的1 ,這是不夠的。

我的下面的代碼服務於我的目的,並在one_counter存儲5 one_counter ,但它看起來很麻煩,對我來說感覺不熟悉。

有什么建議我如何改進其pythonicity並將其擴展到更多維列表?

謝謝!

x = [[1, 2], 1, 1, [2, 1, [1, 2]]]

one_counter = 0

for i in x:
    if type(i) == list:
        for j in i:
            if type(j) == list:
                for k in j:
                    if k == 1:
                        one_counter += 1

            else:
                if j == 1:
                    one_counter += 1

    else:
        if i == 1:
            one_counter += 1

你可以使用遞歸:

def flatten_count(iterable, element):
    count = 0
    for item in iterable:
        if item == element:
            count += 1
        if isinstance(item, list):
            count += flatten_count(item, element)
    return count

或者更簡潔:

def flatten_count(iterable, element):
    return sum(
        flatten_count(item, element) if isinstance(item, list) else item == element
        for item in iterable 
    )

使用這樣:

>>> x = [[1, 2], 1, 1, [2, 1, [1, 2]]]
>>> print(flatten_count(x, 1))
5

一個hacky解決方案,通過將數據類型轉換為字符串來工作: http//codepad.org/vNEv6B8M

import re
x = [ [1, 2], 1, 1, [2, 1, [1, 2]] ]
nums = [int(i) for i in re.findall(r'\d+', str(x))]
print(nums.count(1))

我認為最好將這項任務分為兩部分。

第1部分

第1部分是創建一個生成器,它將輸入列表展平。

def flatten_list(L):
    for i in L:
        if isinstance(i,list):
            for j in flatten_list(i):
                yield j
        else:
            yield i

測試輸出:

x = [[1, 2], 1, 1, [2, 1, [1, 2]]]

for i in flatten_list(x):
    print i

輸出:

1
2
1
1
2
1
1
2

第2部分

部2是使用扁平的列表來計數的發生次數1在它:

print(sum(i==1 for i in flatten_list(x))) 

輸出:

5

請注意, i==1返回True ,如果i=1 ,和False ,如果i不等於1 True等於1False等於0 ,所以sum剛剛計算的數量True出現(其等於5在這種情況下)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM