【问题标题】:Counting sub-element in string?计算字符串中的子元素?
【发布时间】:2017-02-25 03:36:52
【问题描述】:

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

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

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

我必须做些什么来确保我可以找到整个单词的长度,而不是单个元素的长度?

【问题讨论】:

  • 所以将string.split()结果存储在一个新变量中,并取that的第一个元素的长度。
  • @MartijnPieters 我正在尝试,但我得到了SyntaxError: can't assign to function call
  • 听起来你在某处得到了分配错误的语法。看我的回答。

标签: python list string-length


【解决方案1】:

您取了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

【讨论】:

  • 哦,我现在明白了!我没有把变量按顺序排列。非常感谢!
【解决方案2】:

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

关于你的陈述...

我想统计字符串中的每个单词

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

【讨论】:

    【解决方案3】:
    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
    

    【讨论】:

    • 那么,d = {word : len(word) for word in words}?为什么是默认字典?
    • 谢谢我试图以更易读的方式编写它。我已经更改了答案,非常感谢您的建议。
    猜你喜欢
    • 2020-10-23
    • 1970-01-01
    • 2022-10-15
    • 2023-03-28
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    相关资源
    最近更新 更多