python list comprehensions; compressing a list of lists?

后端 未结 13 1822
名媛妹妹
名媛妹妹 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:22

    You can concatenate lists using the normal addition operator:

    >>> [1, 2] + [3, 4]
    [1, 2, 3, 4]
    

    The built-in function sum will add the numbers in a sequence and can optionally start from a specific value:

    >>> sum(xrange(10), 100)
    145
    

    Combine the above to flatten a list of lists:

    >>> sum([[1, 2], [3, 4]], [])
    [1, 2, 3, 4]
    

    You can now define your flatmap:

    >>> def flatmap(f, seq):
    ...   return sum([f(s) for s in seq], [])
    ... 
    >>> flatmap(range, [1,2,3])
    [0, 0, 1, 0, 1, 2]
    

    Edit: I just saw the critique in the comments for another answer and I guess it is correct that Python will needlessly build and garbage collect lots of smaller lists with this solution. So the best thing that can be said about it is that it is very simple and concise if you're used to functional programming :-)

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