迭代 python 集中的单个元素
Iterate individual elements in python sets
给定 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
是否有更多neater/elegant方式迭代集合中的单个元素?
您可以简单地使用 collections.Counter
and itertools.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
计算每个项目出现的次数,并将该项目及其计数维护为字典。
然后 most_common(1)
调用 Counter
returns 一个项目列表,顶部 n
(传递给它的参数)最大出现次数,格式为 (item, count)
。由于我们只对该项目感兴趣,因此我们 return 第一个项目 [0][0]
。
仅使用 built-ins,没有标准库导入:
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
给定 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
是否有更多neater/elegant方式迭代集合中的单个元素?
您可以简单地使用 collections.Counter
and itertools.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
计算每个项目出现的次数,并将该项目及其计数维护为字典。
然后 most_common(1)
调用 Counter
returns 一个项目列表,顶部 n
(传递给它的参数)最大出现次数,格式为 (item, count)
。由于我们只对该项目感兴趣,因此我们 return 第一个项目 [0][0]
。
仅使用 built-ins,没有标准库导入:
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