【问题标题】:list comprehension to split string and return string and its length列表理解拆分字符串并返回字符串及其长度
【发布时间】:2019-12-23 22:35:37
【问题描述】:

我有一个字符串,我希望通过在我的列表理解中使用元组(单词,长度)来使用列表理解来打印具有偶数个字母的单词。我尝试了这样的方法来返回包含偶数个字母的单词元组列表:

sentence = 'If you dont actually care about collecting all the strings in a list using a list comprehension doesnt make much sense'

word_with_even_letters = [(word,len(word)) in sentence.split() if len(word)==0]

实际结果:

文件“”,第 2 行 word_with_even_letters = [(word,len(word)) in sentence.split() if len(word)==0] ^ SyntaxError: 无效语法

预期结果:列表 word_with_even_letters 应包含以下元组:

(If,2)
(dont,4)
(actually,8)
(care,4)
(collecting,10)
(in,2)
(list,4)
(doesnt,6)
(make,4)
(much,4)

【问题讨论】:

    标签: python-3.x list tuples list-comprehension


    【解决方案1】:

    您需要在列表理解中使用for 语句,并检查一个数字是否甚至不测试n == 0,而是测试n % 2 == 0

    sentence = 'If you dont actually care about collecting all the strings in a list using a list comprehension doesnt make much sense'
    
    word_with_even_letters = [(word, len(word)) for word in sentence.split() if len(word) % 2 == 0]
    
    print(word_with_even_letters)
    

    输出:

    [('If', 2), ('dont', 4), ('actually', 8), ('care', 4), ('collecting', 10), ('in', 2), ('list', 4), ('list', 4), ('doesnt', 6), ('make', 4), ('much', 4)]
    

    【讨论】:

    • 谢谢。是的,我错过了 %2 和 for 语句。
    【解决方案2】:

    缺少一条命令:

    word_with_even_letters = [(word,len(word)) for word in sentence.split() if len(word)%2==0]
    

    【讨论】:

      【解决方案3】:
      sentence.split()
      

      是一个迭代,你必须使用它的项, 请将您的代码更改为:

      sentence = 'If you dont actually care about collecting all the strings in a list using a list comprehension doesnt make much sense'
      
      word_with_even_letters = list((word,len(word)) for word in sentence.split() if len(word)%2==0)
      
      print(word_with_even_letters)
      

      【讨论】:

        猜你喜欢
        • 2019-06-13
        • 1970-01-01
        • 1970-01-01
        • 2012-11-20
        • 1970-01-01
        • 2011-12-13
        • 1970-01-01
        • 1970-01-01
        • 2020-04-14
        相关资源
        最近更新 更多