计算字符串中的子元素?

Counting sub-element in string?

说我有一个 string = "Nobody will give me pancakes anymore"

我想计算字符串中的每个单词。所以我 string.split() 得到一个列表以获得 ['Nobody', 'will', 'give', 'me', 'pancakes', 'anymore'].

但是当我想通过输入len(string[0])知道'Nobody'的长度时它只给我1,因为它认为第0个元素只是'N'而不是 'Nobody'

我需要做什么才能确保找到整个单词的长度,而不是单个元素的长度?

您使用了 string[0] 的第一个字母,忽略了 string.split() 调用的结果。

存储拆分结果;这是一个包含单个单词的列表:

words = string.split()
first_worth_length = len(words[0])

演示:

>>> string = "Nobody will give me pancakes anymore"
>>> words = string.split()
>>> words[0]
'Nobody'
>>> len(words[0])
6

是的,string[0] 就是 'N'

关于您的声明...

I want to count each word in the string

>>> s = "Nobody will give me pancakes anymore"
>>> lens = map(lambda x: len(x), s.split())
>>> print lens
[6, 4, 4, 2, 8, 7]

所以,那么你可以lens[0]

words = s.split()   
d = {word : len(word) for word in words}

or

words = s.split()
d = {}

for word in words:
    if word not in d:
        d[word]=0
    d[word]+=len(word)

In [15]: d  
Out[15]: {'me': 2, 'anymore': 7, 'give': 4, 'pancakes': 8, 'Nobody': 6,   'will': 4}
In [16]: d['Nobody']
Out[16]: 6