【问题标题】:Iterate individual elements in python sets迭代python集中的单个元素
【发布时间】:2016-04-20 22:44:57
【问题描述】:

给定 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

是否有一种更简洁/优雅的方式来遍历集合中的各个元素?

【问题讨论】:

  • 你的意思是set 中的m tuplesn 元素吗?
  • 对于初学者,for i in range(0,len(pair)): 应该只是 for i in pair:
  • 是的,假设 m = 4 和 n = 2 那么输入是 input_set = {(5,4),(3,2),(4,3),(8,3)}跨度>

标签: python python-2.7 set iteration hashtable


【解决方案1】:

你可以简单地使用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) 调用返回一个列表,其中包含 top n(传递给它的参数)出现次数最多的项目列表,格式为 (item, count)。由于我们只对项目感兴趣,因此我们将第一个项目返回为[0][0]

【讨论】:

    【解决方案2】:

    仅使用内置函数,不使用标准库导入:

    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 你能解释一下 hash_table.get(item, 0)
    猜你喜欢
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-20
    • 1970-01-01
    相关资源
    最近更新 更多