-2

これを1行で行う方法。

   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))

使用mapは少し速くなります(そして@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 に答える