【问题标题】:Function to return number of pairs of items within input list返回输入列表中项目对数的函数
【发布时间】:2020-05-06 14:12:56
【问题描述】:

我正在尝试编写一个函数来计算给定列表中每种颜色的对数作为输入。我试图得到这个输出,但我不知道如何识别列表中的对。

输入:

['red','yellow','blue','blue','red','blue']

输出:

1 pair of red, 1 pair of blue

【问题讨论】:

    标签: python python-3.x algorithm list counting


    【解决方案1】:

    一种方法是使用collections.Counter

    代码:

    from collections import Counter
    
    def find_pairs(socks):
        c = Counter(socks)
        pairs = dict()
        for k, v in c.items():
            if v >= 2:
                pairs[k] = v//2
        return pairs
    
    socks = ['red','yellow','blue','blue','red','blue']
    
    pairs = find_pairs(socks)
    
    for colour, num_pairs in pairs.items():
        print(f"{num_pairs} pairs of {colour}")
    

    输出:

    1 pairs of red
    1 pairs of blue
    

    【讨论】:

    • 非常感谢我亲爱的朋友的帮助。它对我意义重大。亲爱的朋友,有没有其他方法可以在不使用任何内置模块的情况下解决这个问题,比如这里我们使用了collection.counter。我对 Python 很陌生。提前致谢。
    猜你喜欢
    • 2020-02-24
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多