简体   繁体   中英

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

I have a list of elements of two strings and a space. I would like to count the unique number of elements and order the list.

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

So would like to get the following:

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

I've tried the following but it seems to create multiple redundant lists:

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

Any help is appreciated. Thanks!

This seems to be about what you're looking for:

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

On a side note, tuples are immutable and generally not the best tool for counting.

This should do it:

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)

So, we use set(plist) to create a set (this is a list, in which each unique element of plist only appears once. Then we use the count function to count the number of occurences of each unique element in the original plist. After that we sort based on the second element (using the lambda function). Reverse is set to True, so that the element with most occurences comes first.

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM