计算字符串列表中的数字并将其作为整数列表返回

2024-09-29 19:30:14 发布

您现在位置:Python中文网/ 问答频道 /正文

新来的。请看一下我的docstring,看看我想做什么:

def count(data):
    """ (list of list of str) -> list of int

    Return the numbers of occurrences of strings that end in digits 0, 1, or 2
    for each string.

    >>> data = [['N', 'OW1'], ['Y', 'EH1', 'S'], ['AW1', 'OW1']]
    >>> count(data)
    [1, 1, 2]
    """

    num_list = []
    num = 0

    for sublist in phonemes:
        for item in sublist:
            if item[-1].isdigit():
                num += 1
        num_list.append(num)
    return num_list 

我不知道如何为每个datasublist创建一个数字。这是正确的方法吗?任何帮助都会很好。你知道吗


Tags: ofinfordatareturndefcountitem
3条回答

通过你的理解。你知道吗

>>> data = [['N', 'OW1'], ['Y', 'EH1', 'S'], ['AW1', 'OW1']]
>>> [len([j for j in i if j[-1] in "012"]) for i in data]
[1, 1, 2]

我认为您的想法是正确的,但在完成子列表后,您不会将num重置为0。现在要做的是计算所有子列表中的数字0,1,2的总数。您需要的是每个子列表的计数。你知道吗

在遍历整个子列表之后,还必须附加num。所以你需要把它从内部for循环体中去掉。你知道吗

修订日期:

def count(data):
    """ (list of list of str) -> list of int

    Return the numbers of occurrences of strings that end in digits 0, 1, or 2
    for each string.

    >>> data = [['N', 'OW1'], ['Y', 'EH1', 'S'], ['AW1', 'OW1']]
    >>> count(data)
    [1, 1, 2]
    """

    num_list = []
    num = 0

    for sublist in data:
        for item in sublist:
            if item[-1] in "012":
                num += 1

        # item in sublist body is over
        # num is now total occurrences of 0,1,2 in sublist
        num_list.append(num)
        num = 0
    return num_list 

print count([['N', 'OW1'], ['Y', 'EH1', 'S'], ['AW1', 'OW1']])

试试这个。你知道吗

def count(data):
    """ (list of list of str) -> list of int

    Return the numbers of occurrences of strings that end in digits 0, 1, or 2
    for each string.

    >>> data = [['N', 'OW1'], ['Y', 'EH1', 'S'], ['AW1', 'OW1']]
    >>> count(data)
    [1, 1, 2]
    """

    return [ len([item for item  in sublist if item[-1].isdigit()]) for sublist in data]

相关问题 更多 >

    热门问题