【问题标题】:Better way to iterate through list and store output in a new list遍历列表并将输出存储在新列表中的更好方法
【发布时间】:2021-11-08 01:44:35
【问题描述】:

我是 python 的初学者,希望您能就更复杂的方式来编写以下代码提出意见。我希望代码遍历整个项目列表 (x),计算每个项目出现的次数并将输出存储在新列表 (z) 中。这是代码(按原样工作):

x = ["apple", "orange", "cherry", "apple"]

def new_list(a):
    z=[]
    for i in x:
        y = x.count(i)
        (z.append(y))
    return z

print(new_list(x)) 

【问题讨论】:

    标签: python list loops


    【解决方案1】:

    尝试使用 Counter 类:

    from collections import Counter
    x = ["foo", "bar", "foo", "foo"];
    z = Counter(x)
    print(z)
    # Output: {"foo": 3, "bar": 1} 
    

    【讨论】:

    • "尝试使用 Counter 库" -- Counter 是一个类而不是一个库。
    【解决方案2】:

    您可以使用集合模块的 Counter 子类:

    from collections import Counter
    
    x = ["apple", "orange", "cherry", "apple"]
    
    
    counter = Counter(x)
    z = list(counter.values())
    
    print(z) #[2,1,1]
    

    我没有使用count,因为它可能不利于性能,this answer 也指出了这一点。

    【讨论】:

      【解决方案3】:

      使用list.count(),你的编程顺序是O(n^2),使用Counter and hashmap,你的程序员的顺序是O(n)。 试试这个:

      x = ["apple", "orange", "cherry", "apple"]
      
      [x.count(i) for i in x]
      # [2,1,1,2]
      

      或者使用Counter:

      from collections import Counter
      dct = Counter(x)
      # Counter({'apple': 2, 'orange': 1, 'cherry': 1})
      
      [dct[i] for i in x]
      # [2, 1, 1, 2]
      

      检查运行时:Counterlist.count() 快)

      【讨论】:

      • @U12-Forward 等待检查大型列表 :)))
      • @U12-Forward 这是两种方法,不是我的和你的,我确定Counter is O(n)count is O(n^2)
      • 好吧 Counter 不满足 Op 的期望输出。
      • @U12-Forward 可以更快地看到计数器 1000
      • map怎么样
      【解决方案4】:

      您可以在集合中使用 Counter 类。所以遍历输入列表,然后找到每个元素的计数。

      from collections import Counter
      x = ["apple", "orange", "cherry", "apple"]
      c = Counter(x)
      print([c[item] for item in x])
      #[2, 1, 1, 2]
      

      【讨论】:

        【解决方案5】:

        我建议做一个列表理解:

        >>> x = ["apple", "orange", "cherry", "apple"]
        >>> [x.count(val) for val in x]
        [2, 1, 1, 2]
        >>> 
        

        map 甚至更好:

        >>> [*map(x.count, x)]
        [2, 1, 1, 2]
        >>> 
        

        【讨论】:

          猜你喜欢
          • 2015-05-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-07-16
          • 1970-01-01
          • 1970-01-01
          • 2018-11-20
          • 1970-01-01
          相关资源
          最近更新 更多