python list comprehensions; compressing a list of lists?

后端 未结 13 1819
名媛妹妹
名媛妹妹 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.

    0 讨论(0)
  • 2020-11-30 02:04

    You can find a good answer in itertools' recipes:

    def flatten(listOfLists):
        return list(chain.from_iterable(listOfLists))
    

    (Note: requires Python 2.6+)

    0 讨论(0)
  • 2020-11-30 02:05
    If listA=[list1,list2,list3]
    flattened_list=reduce(lambda x,y:x+y,listA)
    

    This will do.

    0 讨论(0)
  • 2020-11-30 02:06

    You can have nested iterations in a single list comprehension:

    [filename for path in dirs for filename in os.listdir(path)]
    

    which is equivalent (at least functionally) to:

    filenames = []
    for path in dirs:
        for filename in os.listdir(path):
            filenames.append(filename)
    
    0 讨论(0)
  • 2020-11-30 02:09

    Google brought me next solution:

    def flatten(l):
       if isinstance(l,list):
          return sum(map(flatten,l))
       else:
          return l
    
    0 讨论(0)
  • 2020-11-30 02:13
    subs = []
    map(subs.extend, (os.listdir(d) for d in dirs))
    

    (but Ants's answer is better; +1 for him)

    0 讨论(0)
提交回复
热议问题