📜  Python – 混合嵌套元组中的元素频率

📅  最后修改于: 2022-05-13 01:55:15.170000             🧑  作者: Mango

Python – 混合嵌套元组中的元素频率

有时,在处理Python数据时,我们可能会遇到一个问题,即我们在单个元组中包含嵌套和非嵌套形式的数据,我们希望计算其中的元素频率。这类问题可能出现在 Web 开发和数据科学等领域。让我们讨论可以执行此任务的某些方式。

方法#1:使用递归+循环
这个问题的解决包括两个步骤。首先,我们使用递归对元组进行扁平化,然后使用循环以蛮力方式执行计数。

# Python3 code to demonstrate working of 
# Elements Frequency in Mixed Nested Tuple
# Using recursion + loop
  
# helper_fnc
def flatten(test_tuple):
    for tup in test_tuple:
        if isinstance(tup, tuple):
            yield from flatten(tup)
        else:
            yield tup
  
# initializing tuple
test_tuple = (5, 6, (5, 6), 7, (8, 9), 9)
  
# printing original tuple
print("The original tuple : " + str(test_tuple))
  
# Elements Frequency in Mixed Nested Tuple
# Using recursion + loop
res = {}
for ele in flatten(test_tuple):
    if ele not in res:
        res[ele] = 0
    res[ele] += 1
  
# printing result 
print("The elements frequency : " + str(res))
输出 :
The original tuple : (5, 6, (5, 6), 7, (8, 9), 9)
The elements frequency : {5: 2, 6: 2, 7: 1, 8: 1, 9: 2}

方法#2:使用Counter() + resursion
这是可以解决此问题的另一种方式。在此,我们使用 Counter() 来执行计算元素的任务。

# Python3 code to demonstrate working of 
# Elements Frequency in Mixed Nested Tuple
# Using recursion + Counter()
from collections import Counter
  
# helper_fnc
def flatten(test_tuple):
    for tup in test_tuple:
        if isinstance(tup, tuple):
            yield from flatten(tup)
        else:
            yield tup
  
# initializing tuple
test_tuple = (5, 6, (5, 6), 7, (8, 9), 9)
  
# printing original tuple
print("The original tuple : " + str(test_tuple))
  
# Elements Frequency in Mixed Nested Tuple
# Using recursion + Counter()
res = dict(Counter(flatten(test_tuple)))
  
# printing result 
print("The elements frequency : " + str(res))
输出 :
The original tuple : (5, 6, (5, 6), 7, (8, 9), 9)
The elements frequency : {5: 2, 6: 2, 7: 1, 8: 1, 9: 2}