如何将嵌套列表拆分为两部分?

时间:2015-04-28 18:02:27

标签: python list python-2.7

我有一个大小为M x N的嵌套列表。

_tcslen()

我想以下面的格式拆分它:

 [['12', '23', '56'],
 ['1', '4', '5'],
 ['67', '78', '98']]

2 个答案:

答案 0 :(得分:3)

这是将lsts中所有列表中的最后一项一般删除到新列表removed中的一种方法:

lsts = [['12', '23', '56'],
        ['1', '4', '5'],
        ['67', '78', '98']]

removed = [lst.pop() for lst in lsts]

print(lsts, removed)

输出:

[['12', '23'], ['1', '4'], ['67', '78']] ['56', '5', '98']

http://ideone.com/xphb3P

答案 1 :(得分:1)

这可以通过列表推导来实现:

a = [['12', '23', '56'],
     ['1', '4', '5'],
     ['67', '78', '98']]
l1 = [s[:2] for s in  a]
l2 = [s[2] for s in a]

l1包含[['12', '23'], ['1', '4'], ['67', '78']]

l2 conatins ['56', '5', '98']