簡體   English   中英

用Python計算元組中的唯一字符串

[英]Counting Unique Strings in Tuples, Python

我試圖計算一個元組中的唯一字符串,並僅在列表中輸出唯一字符串及其計數。 我正在嘗試使用列表補償,但是有一些問題:

def tupleTag(inputList):
    from collections import Counter

    c = Counter(inputList[0] for inputList in inputList)
    print set(inputList[0], c)

inputList = [('love','family'),('dinner','family','nomnom'),('wedding','romance','love')]
tupleTag(inputList)      

正確的輸出將是=

[(love,2), (family,2)]

您似乎在collections.Counter的正確軌道上。 我還會拋出itertools.chain

items = itertools.chain.from_iterable(inputList)
counts = collections.Counter(items)

現在,您已經有了一個項目映射到它們出現的次數。 如果要使用格式為(<key>, <count>)的元組的排序列表,則可以使用most_common方法-當然,您可以對其進行過濾,以查找僅重復的字符串及其計數:

repeated_items = [(key, count) for key, count in counts.most_common() if count > 1]

請注意,您實際上並不需要 most_common來過濾項目,但確實會按照常見程度為您提供結果。 如果這不是必需的,則對項目進行簡單循環將更有效:

repeated_items = [(key, count) for key, count in counts.items() if count > 1]

mgilson的答案非常狡猾,值得研究。 這是使用理解的花園多樣化方法:

tups   = ...  # Your data.
c      = Counter(x for tup in tups for x in tup)
result = [(k, n) for k, n in c.items() if n > 1]

暫無
暫無

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

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