我想在python列表中执行此操作。 例如我有一个 列表= [['水果','苹果'] ['水果','桃子'],['水果','香蕉'],['动物','猫'],['动物', '绵羊']]
打印结果应为['apple','peach','banana'],长度= 3
如何编写没有内置功能的算法来做到这一点?
答案 0 :(得分:0)
您想要的结果['apple','peach','banana']不是常见的元素。您可以制作字典来分隔不同类别的对象。
class PollContext(path: String) : ViewModel() {
val pathProperty = SimpleStringProperty(path)
var path by pathProperty
val currentDataProperty = SimpleStringProperty()
var currentData by currentDataProperty
}
这会给你
dict = {}
for item_list in list_of_lists:
if item_list[0] not in dict:
dict[item_list[0]] = []
dict[item_list[0]].append(item_list[1])
else:
dict[item_list[0]].append(item_list[1])
答案 1 :(得分:0)
使用itertools.groupby
对key
进行分组,然后将max
与key
一起使用
例如:
from itertools import groupby
l = [['fruit','apple'], ['fruit','peach'],['fruit','banana'], ['animal', 'cat'],['animal', 'sheep'] ]
s = dict((k, [i[1] for i in v]) for k, v in groupby(l, lambda x: x[0])) #Group by key.
print( max(s.items(), key=lambda x: len(x[1]))[1] ) #Get max item using len
输出:
['apple', 'peach', 'banana']
答案 2 :(得分:0)
您可以使用defaultdict和max:
from collections import defaultdict
data = [['fruit','apple'],['fruit','peach'],['fruit','banana'], ['animal', 'cat'],['animal', 'sheep']]
grouped_data = defaultdict(list)
for key, value in data:
grouped_data[key].append(value)
print(grouped_data)
# defaultdict(<class 'list'>, {'fruit': ['apple', 'peach', 'banana'], 'animal': ['cat', 'sheep']})
most_frequent = max(grouped_data.items(), key=lambda i: len(i[1]))
print(most_frequent)
# ('fruit', ['apple', 'peach', 'banana'])
print(len(most_frequent[1]))
# 3
答案 3 :(得分:0)
如何编写没有内置功能的算法来做到这一点?
如果没有内置函数,您将无法真正做到。我想您只是不想内置集合工具,而是想从头开始编写算法。我认为这不是最好的方法,但是您可以使用这个:
def most_common(somelist: list) -> dict:
somelist_dict = {}
somelist_list = []
result={'mostcommon':'','length':0,'content':[]}
maxi=0
word=''
for x in somelist:
try:
somelist_dict[x[0]].append(x[1])
except:
somelist_dict[x[0]] = []
somelist_list.append(x[0])
somelist_dict[x[0]].append(x[1])
for i, j in enumerate(somelist_list):
if i == 0:
word = j
maxi = len(somelist_dict[j])
else:
tmp = len(somelist_dict[j])
if maxi < tmp:
word = j
maxi = tmp
result["mostcommon"]=word
result['length']=maxi
for k in somelist_dict[word]:
result['content'].append(k)
return result
somelist=[['fruit','apple'],['fruit','peach'],['fruit','banana'],['animal','cat'],['animal','sheep']]
print(most_common(somelist))
输出是:
{'content': ['apple', 'peach', 'banana'], 'length': 3, 'mostcommon': 'fruit'}