2015-04-01 98 views
1

此處新增。請看看我的文檔字符串,看看有什麼我想要做的事:將字符串列表中的數字進行計數並將它們作爲整數列表返回

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造就了一批。這是否是正確的方法?任何幫助都會很棒。

回答

0

我認爲你有正確的想法,但你不重置num 0完成一個子表後。你現在正在做的是計算所有子列表中總數爲0,1,2的數字。你想要的是每個子列表的計數。

在完成整個子列表後,您還必須附加num。所以你需要把它放在循環體內部。

修訂:

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']]) 
+0

這有助於很多。謝謝。 – Sarah 2015-04-01 03:50:51

0

我的解決辦法:

def count(data): 
    nums = [] 
    for sub in data: 
     occur = 0 
     for i in sub: 
      if i.endswith(('0', '1', '2')): 
       occur += 1 
     nums.append(occur) 
    return nums 
2

試試這個。

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] 
+0

不錯的一行。 – pzp 2015-04-01 03:48:44

+2

你可以避免使用'sum'構造中間列表:[sum(1)如果item [-1] .isdigit()爲子列表中的項目, – AChampion 2015-04-01 03:58:21

0
>>> data = [['N', 'OW1'], ['Y', 'EH1', 'S'], ['AW1', 'OW1']] 
>>> the_lengths = [i for i in map(int, [len([i for i in thelist if i[-1].isdigit()]) for thelist in data])] 
>>> the_lengths 
[1, 1, 2] 
1

通過list_comprehension。

>>> 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] 
相關問題