簡體   English   中英

使用Python計算由空格分隔的兩個字符串的唯一列表元素

[英]Using Python to count unique list elements of two strings separated by a space

我有兩個字符串和一個空格的元素列表。 我想計算元素的唯一數量並排序列表。

plist = ('burleson both', 'the largemouth', 'the largemouth', 'a 19inch', 'his first')

所以想得到以下內容:

plist = [('the largemouth',2), ('burleson both', 1), ('a 19inch', 1), ('his first', 1)]

我嘗試了以下操作,但似乎創建了多個冗余列表:

unique_order_list = {}
for item in plist:
    unique_order_list[item] = plist.count(item)
d = OrderedDict(sorted(unique_order_list.items(), key=operator.itemgetter(1), reverse=True))

任何幫助表示贊賞。 謝謝!

這似乎與您要查找的內容有關:

plist = ['burleson both', 'the largemouth', 'the largemouth', 'a 19inch', 'his first']
result = []
def index_finder(string,List):
    answer = 0
    for i in List:
        if i != string:
            answer+=1
        else:
            return answer
def verifier(target,List):
    for i in List:
        if i[0] == target:
            return True
    return False

for each in plist:
    if verifier(each,result):
        result[index_finder(each,plist)]= (each,result[index_finder(each,plist)][1] +1)


    else:
        result.append((each,1))
print result

另外,元組是不可變的,通常不是最好的計數工具。

應該這樣做:

plist = ('burleson both', 'the largemouth', 'the largemouth', 'a 19inch', 'his first')
plist = [(x, plist.count(x)) for x in set(plist)]
plist.sort(key=lambda x: x[1], reverse=True)

因此,我們使用set(plist)創建一個集合(這是一個列表,其中plist的每個唯一元素僅出現一次。然后,我們使用count函數對原始plist中每個唯一元素的出現count進行計數。之后,我們根據第二個元素進行排序(使用lambda函數),將reverse設置為True,以便出現次數最多的元素排在第一位。

嘗試這個:

import collections

plist = ('burleson both', 'the largemouth', 'the largemouth', 'a 19inch', 'his first')

counts = collections.Counter(plist)

print counts # Counter({'the largemouth': 2, 'a 19inch': 1, 'burleson both': 1, 'his first': 1})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM