【问题标题】:Using Python to count unique list elements of two strings separated by a space使用 Python 计算由空格分隔的两个字符串的唯一列表元素
【发布时间】:2014-10-24 15:04:31
【问题描述】:

我有一个包含两个字符串和一个空格的元素列表。我想计算元素的唯一数量并对列表进行排序。

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

感谢任何帮助。谢谢!

【问题讨论】:

  • 'the largemouth', 'for largemouth' - 他们都一样吗?
  • 你能把问题说清楚一点吗?你说你想计算“元素的唯一数量”,这是什么意思? 'the largemouth' 和 'for largemouth' 不一样,你将它们算作相同,但在 'the largemouth' 下。我们需要更多背景信息。
  • 抱歉,我更新了问题。 'the largemouth' 元素应该在那里出现两次。
  • @user2743 您正在使用OrderedDict,但largemouthburleson both 仍然出现故障。为什么?

标签: python list ordereddictionary


【解决方案1】:

应该这样做:

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】:

    这似乎与您正在寻找的内容有关:

    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
    

    附带说明,元组是不可变的,通常不是计算的最佳工具。

    【讨论】:

      【解决方案3】:

      试试这个:

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

      【讨论】:

        猜你喜欢
        • 2014-12-05
        • 1970-01-01
        • 1970-01-01
        • 2019-04-10
        • 2021-07-13
        • 2019-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多