简体   繁体   English

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

[英]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. 因此,我们使用set(plist)创建一个集合(这是一个列表,其中plist的每个唯一元素仅出现一次。然后,我们使用count函数对原始plist中每个唯一元素的出现count进行计数。之后,我们根据第二个元素进行排序(使用lambda函数),将reverse设置为True,以便出现次数最多的元素排在第一位。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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