python list comprehensions; compressing a list of lists?

后端 未结 13 1821
名媛妹妹
名媛妹妹 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 02:18

    You could try itertools.chain(), like this:

    import itertools
    import os
    dirs = ["c:\\usr", "c:\\temp"]
    subs = list(itertools.chain(*[os.listdir(d) for d in dirs]))
    print subs
    

    itertools.chain() returns an iterator, hence the passing to list().

    0 讨论(0)
  • 2020-11-30 02:18
    def flat_list(arr):
        send_back = []
        for i in arr:
            if type(i) == list:
                send_back += flat_list(i)
            else:
                send_back.append(i)
        return send_back
    
    0 讨论(0)
  • 2020-11-30 02:20
    >>> from functools import reduce
    >>> listOfLists = [[1, 2],[3, 4, 5], [6]]
    >>> reduce(list.__add__, listOfLists)
    [1, 2, 3, 4, 5, 6]
    

    I'm guessing the itertools solution is more efficient than this, but this feel very pythonic.

    In Python 2 it avoids having to import a library just for the sake of a single list operation (since reduce is a built-in).

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

    You could just do the straightforward:

    subs = []
    for d in dirs:
        subs.extend(os.listdir(d))
    
    0 讨论(0)
  • 2020-11-30 02:20

    You can use pyxtension:

    from pyxtension.streams import stream
    stream([ [1,2,3], [4,5], [], [6] ]).flatMap() == range(7)
    
    0 讨论(0)
  • 2020-11-30 02:21
    import itertools
    x=[['b11','b12'],['b21','b22'],['b31']]
    y=list(itertools.chain(*x))
    print y
    

    itertools will work from python2.3 and greater

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