一个返回namedtuple的函数

时间:2015-11-09 02:34:30

标签: python python-3.x

我必须编写一个带有2个参数并返回一个namedtuple的函数。

Count = namedtuple('Count', 'letter number')

该函数应该返回:

>>> letter_count('The cabbage has baggage', 'abcd')
[Count(letter='a',number=5), Count(letter='b',number=3), Count(letter='c',number=1), Count(letter='d',number=0)]

到目前为止,我有:

from collections import namedtuple
Count = namedtuple('Count', 'letter number')
def letter_count(x: str, a: str):

    for letter in a:
        letter = Count.letter
        for letters in x:
            if letter == letters:
                Count.number = len(letter)

    return Count

但我得到了

<class '__main__.Count'>

2 个答案:

答案 0 :(得分:1)

您需要使用位置或关键字参数来实例化namedtuple

此外,使用计数器计数器,它很简单,具有高性能。您可以查看手册了解详情。

试试这个:

import collections

Count = collections.namedtuple('Count', 'letter, number')

def letter_count(letters, target):
    counter = collections.Counter(letters)
    return [Count(c, counter[c]) for c in target]  # instantiate Count like Count(letter, number)

输出:

>>> letter_count('The cabbage has baggage', 'abcd')
[Count(letter='a', number=5), Count(letter='b', number=3), Count(letter='c', number=1), Count(letter='d', number=0)]

答案 1 :(得分:0)

另一种非常简单的方法,不需要collections.Counter

from collections import namedtuple

Count = namedtuple('Count', 'letter number')

def letter_count(s: str, letters: str):
    return [Count(letter, s.count(letter)) for letter in letters]

print(letter_count('The cabbage has baggage', 'abcd'))

输出:

[Count(letter='a', number=5), Count(letter='b', number=3), Count(letter='c', number=1), Count(letter='d', number=0)]

然而,这并未考虑区分大小写。因此Tt会有单独的计数值。