繁体   English   中英

将代码转换为python列表理解

[英]Convert code to python list comprehension

像这样的代码:

class H:
    def __init__(self, row):
        self.row = row

    @staticmethod
    def gg(word):
        if not word:
            return 0
        return 1

    def ff(self):
        l = []                         # return [sentence for sentence in self.row.split('/') for word in self.gg(sentence.split(' '))]
        for sentence in self.row.split('/'):
            num_of_syllables = 0
            for word in sentence.split(' '):
                num_of_syllables += self.gg(word)
            l.append(num_of_syllables)
        return l

是否可以缩短上述 coe 并用于列出函数 ff() 中的理解?

return [sentence for sentence in self.row.split('/') for word in self.gg(sentence.split(' '))]

像这样计算真值的一件非常有用的事情是boolintTrue == 1False == 0的子类

def ff(self):
    return [
        sum(bool(word) for word in sentence.split(' '))
        for sentence in self.row.split('/')
    ]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM