简体   繁体   中英

Convert code to python list comprehension

Code like that:

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

Is it possible to shorten above coe and use to list comprehension in function ff()?

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

One very useful thing for counting truthy values like this is the fact that bool is a subclass of int , True == 1 and False == 0

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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