查找列表Python的子列表的长度

时间:2017-10-21 21:57:46

标签: python list

我正在编写一个程序,需要在列表的子列表中找出单词的长度,然后将它们一起添加。目前我所拥有的代码可以将列表中的单词分成单个单词,现在我需要找到子列表中单个单词的长度。每当我使用counter_split_list时,它会计算句子中的单词。

这是我的代码:


<meta name="viewport" content="width=device-width, initial-scale=1.0">

Words in Sublists

1 个答案:

答案 0 :(得分: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]]