使用Python计算由空格分隔的两个字符串的唯一列表元素

时间:2014-10-24 15:04:32

标签: python list ordereddictionary

我有两个字符串和一个空格的元素列表。我想计算元素的唯一数量并订购列表。

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))

感谢任何帮助。谢谢!

3 个答案:

答案 0 :(得分:0)

这似乎是关于你正在寻找的东西:

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

另一方面,元组是不可变的,通常不是计数的最佳工具。

答案 1 :(得分:0)

这应该这样做:

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中的每个唯一元素。之后我们根据第二个元素(使用lambda函数)进行排序.Reverse设置为True,因此具有最多出​​现次数的元素首先出现。

答案 2 :(得分:0)

试试这个:

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})
相关问题