2017-10-21 80 views
0

我正在編寫一個程序,需要計算出列表子列表中的單詞長度,然後將它們相加。目前我所擁有的代碼可以將單詞列表分解爲單個單詞,現在我需要查找子單元中單個單詞的長度。每當我使用counter_split_list時,它都會計算句子中的單詞。查找列表子列表的長度Python

這裏是我的代碼:

def split_by_whitespace (['It', 'is', 'a', 'truth', 'universally', 'acknowledged'], ['that', 'a', 'single', 'man', 'in', 'possession', 'of', 'a', 'good', 'fortune', 'must', 'be', 'in', 'want', 'of', 'a', 'wife']): 
    l = my_string 
    split_list =[i.split() for i in l] 
    #counter_split_list=[len(i) for i in split_list] 
    return(split_list) 

Words in Sublists

+0

什麼是你想要的輸出? – Ajax1234

+0

給出'my_string'的例子,你看到的結果以及你想要的結果。 –

+1

嘗試'[len(word)for lst in split_list for word in lst]''。但我不建議一個班輪。 – Rockybilly

回答

0

我想,你的輸入不是字符串,但列出的清單。這些子列表包含您的輸入示例中顯示的單詞。如果是這樣的話,那麼下面的函數會根據你的需要返回每個單詞的長度。

# Modified version of your function 

def split_by_whitespace (my_string): 
    sentence_all_len = [] 
    for sentence in my_string: 
    sentence_len = [len(word) for word in sentence] 
    sentence_all_len.append(sentence_len) 
    return sentence_all_len 

# I assume your input looks like this as you provided in your question, though in a wrong way. 
list_of_strings = [['It', 'is', 'a', 'truth', 'universally', 'acknowledged'], ['that', 'a', 'single', 'man', 'in', 'possession', 'of', 'a', 'good', 'fortune', 'must', 'be', 'in', 'want', 'of', 'a', 'wife']] 

# Output statement with a call to your function with the list of lists as an input 
print(split_by_whitespace(list_of_strings) 

輸出:

[[2, 2, 1, 5, 11, 12], [4, 1, 6, 3, 2, 10, 2, 1, 4, 7, 4, 2, 2, 4, 2, 1, 4]]