在Python集合中迭代单个元素

4

假设有m个包含n个元素的集合

我有下面的代码,可以输出出现次数最多的元素。

def find_element_which_appeared_in_max_sets(input_set):

    hash_table = {}

    # count the frequencies
    for pair in input_set:
        for i in range(0,len(pair)):
            if pair[i] in hash_table:
                hash_table[pair[i]] = hash_table[pair[i]] + 1
            else:
                hash_table[pair[i]] = 1 # first occurence

    # scan and find the element with highest frequency.
    max_freq = 0
    for elem in hash_table:

        if hash_table[elem] > max_freq:
            max_freq = hash_table[elem]
            max_occured_elem = elem

    return max_occured_elem


input_set = {(5,4),(3,2),(4,3),(8,3)}
print ""+str(find_element_which_appeared_in_max_sets(input_set))

输出:

3

在迭代集合中的单个元素方面,有没有更加简洁/优雅的方式?


你是指一组包含n个元素的m个元组的“集合”吗? - gtlambert
对于初学者来说,for i in range(0,len(pair)): 可以简化为 for i in pair: - Ayush
是的,假设m = 4,n = 2,则输入为input_set = {(5,4),(3,2),(4,3),(8,3)}。 - KurinchiMalar
2个回答

4
您可以简单地使用 collections.Counteritertools.chain.from_iterable,像这样:
def find_element_which_appeared_in_max_sets(input_set):
    return Counter(chain.from_iterable(input_set)).most_common(1)[0][0]
chain.from_iterable(input_set)会将输入的元组集合展开成一个单一的可迭代对象,逐个地从每个元组中获取值。
然后,Counter计算每个项出现的次数,并将项及其计数作为字典进行维护。
接下来,对Counter调用most_common(1),返回一个列表,其中包含出现次数最多的前n个项(传递给它的参数),格式为(item, count)。由于我们只关心项,因此返回第一个项[0][0]

4

仅使用内置功能,不使用标准库导入:

def find_element_which_appeared_in_max_sets(input_set):
    hash_table = {}
    for pair in input_set:
        for item in pair:
            #enhanced as proposed by thefourtheye
            hash_table[item] = hash_table.get(item, 0) + 1
    max_occured_element = max(hash_table, key=hash_table.get)
    return max_occured_element

你的 if..else 可以被这个 hash_table[item] = hash_table.get(item, 0) + 1 替代。 - thefourtheye
@thefourtheye 你能解释一下 hash_table.get(item, 0) 吗? - KurinchiMalar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接