如何使用列表理解从列表中列出单个列表?

时间:2012-05-04 10:25:06

标签: python list python-3.x

如何在一行中完成此操作。

   b=[['1','2','3','4','5'],['11','12','13','14','15'],['6','7','8','9','10']]
   c=[]
   for x in b:
        for y in x:
            c.append(int(y))
   c.sort()
   print(c)

预期产出:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

3 个答案:

答案 0 :(得分:8)

>>> b=[['1','2','3','4','5'],['11','12','13','14','15'],['6','7','8','9','10']]
>>> sorted(int(j) for i in b for j in i)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

答案 1 :(得分:3)

import itertools
c = sorted(int(a) for a in itertools.chain(*b))

或者,正如@jamylak正确指出:

import itertools
c = sorted(int(a) for a in itertools.chain.from_iterable(b))

使用map的速度要快一点(并且比@ jamylak的答案中的双列表理解速度快):

import itertools
c = sorted(map(int, itertools.chain.from_iterable(b)))

答案 2 :(得分:2)

另一种变化

>>> from itertools import chain
>>> b=[['1','2','3','4','5'],['11','12','13','14','15'],['6','7','8','9','10']]
>>> sorted(chain(*b),key=int)
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15']

如果你想要一个整数列表,那么

>>> sorted(map(int,chain(*b)))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

速度比较

>>> t1=Timer(stmt='sorted(map(int,chain(*b)))',setup='from __main__ import b;from itertools import chain')
>>> t2=Timer(stmt='sorted(int(i) for l in b for i in l)',setup='from __main__ import b')
>>> t3=Timer(stmt='sorted(int(a) for a in chain(*b))',setup='from __main__ import b;from itertools import chain')
>>> print "%.2f usec/pass" % (1000000 * t1.timeit(number=100000)/100000)
33.23 usec/pass
>>> print "%.2f usec/pass" % (1000000 * t2.timeit(number=100000)/100000)
35.60 usec/pass
>>> print "%.2f usec/pass" % (1000000 * t3.timeit(number=100000)/100000)
36.19 usec/pass