python list comprehensions; compressing a list of lists?

后端 未结 13 1982
名媛妹妹
名媛妹妹 2020-11-30 01:49

guys. I\'m trying to find the most elegant solution to a problem and wondered if python has anything built-in for what I\'m trying to do.

What I\'m doing is this. I

13条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 01:59

    The question proposed flatmap. Some implementations are proposed but they may unnecessary creating intermediate lists. Here is one implementation that's based on iterators.

    def flatmap(func, *iterable):
        return itertools.chain.from_iterable(map(func, *iterable))
    
    In [148]: list(flatmap(os.listdir, ['c:/mfg','c:/Intel']))
    Out[148]: ['SPEC.pdf', 'W7ADD64EN006.cdr', 'W7ADD64EN006.pdf', 'ExtremeGraphics', 'Logs']
    

    In Python 2.x, use itertools.map in place of map.

提交回复
热议问题