-2

如何在一行中做到这一点。

   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]
4

3 回答 3

9
>>> 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]
于 2012-05-04T10:27:12.693 回答
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))

usingmap稍微快一点(并且比@jamylak 的答案中的双重列表理解更快):

import itertools
c = sorted(map(int, itertools.chain.from_iterable(b)))
于 2012-05-04T10:26:29.170 回答
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
于 2012-05-04T10:29:59.050 回答