我想知道如何對串列進行排序:
list_1 = ['apple', 'grape', 'orange', 'orange', 'apple', 'grape', 'apple']
對此:
list_1 = [['apple', 'apple', 'apple'], ['grape', 'grape'], ['orange', 'orange']]
僅使用原始演算法而不是任何排序函式。
原因是我會將此演算法與基于文本相似程度匹配字串的函式結合使用,因為我正在排序的字串不一樣,并且依賴任何排序函式都不允許我使用該功能
非常感謝任何指導和幫助!
uj5u.com熱心網友回復:
你可以使用這種演算法。首先使用任何排序演算法對串列進行排序,現在讓我們使用冒泡排序。然后計算所有元素的頻率并將其存盤在字典中,然后將其轉換回嵌套串列。所以你可以做這樣的事情:
def bubble_sort(ls):
swapped = True
while swapped:
swapped = False
for i in range(len(ls) - 1):
if ls[i] > ls[i 1]:
# Swap the elements
ls[i], ls[i 1] = ls[i 1], ls[i]
swapped = True
return ls
def nest(ls):
ls2 = {}
res = []
for i in ls:
if i in ls2:
ls2[i] = 1
else:
ls2[i] = 1
i = 0
while i<len(ls):
res.append([ls[i]]*ls2[ls[i]])
i =ls2[ls[i]]
return res
print(nest(bubble_sort(['apple', 'grape', 'orange', 'orange', 'apple', 'grape', 'apple'])))
uj5u.com熱心網友回復:
要對該串列進行排序,您可以運行以下代碼:
list_1 = ['apple', 'grape', 'orange', 'orange', 'apple', 'grape', 'apple']
list_1.sort()
dictionary = {}
for item in list_1:
if item not in dictionary:
dictionary[item] = 1
else:
dictionary[item] = 1
list_1 = []
for word in dictionary:
list_2 = [word]*dictionary[word]
list_1.append(list_2)
print(list_1)
這輸出
[['apple', 'apple', 'apple'], ['grape', 'grape'], ['orange', 'orange']]
第二行代碼是可選的,如果您不需要最后一個串列按字母順序排列,您可以將其洗掉。
uj5u.com熱心網友回復:
假設您的單詞相似度函式是可傳遞的,您可以逐步將單詞添加到它們所屬的組中,同時添加新的組來查找沒有任何相似性的單詞:
def groupWords(L,isSimilar=lambda a,b:a==b):
result = []
for word in L: # for each word in list
for group in result: # find a similar word group
if isSimilar(word,group[0]):
group.append(word) # add to the group
break
else:
result.append([word]) # new group if no match
return result
輸出:
list_1 = ['apple', 'grape', 'orange', 'orange', 'apple', 'grape', 'apple']
list_2 = groupWords(list_1)
print(list_2)
[['apple', 'apple', 'apple'], ['grape', 'grape'], ['orange', 'orange']]
您可以為該功能提供您自己的相似性檢查功能或直接使其成為回圈的一部分
請注意,如果您的相似性檢查不具有傳遞性,則單詞將進入第一個匹配組,結果將取決于輸入的順序
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/411312.html
標籤:
