Python嵌套列表切片

时间:2013-12-12 11:22:51

标签: python list slice

我的清单:

>>> l = [["A", "A1", 1, 2, 3], 
         ["B", "A2", 4, 5, 6], 
         ["C", "A3", 7, 8, 9], 
         ["D", "A4", 10, 11, 12]]

切片操作:

>>> [[n[0] for n in l], [u[1:] for u in l]]
[['A', 'B', 'C', 'D'], 
  [['A1', 1, 2, 3], 
  ['A2', 4, 5, 6], 
  ['A3', 7, 8, 9], 
  ['A4', 10, 11, 12]]]

有没有办法在没有额外方括号的情况下切割此列表?如下所示:

[['A', 'B', 'C', 'D'], 
 ['A1', 1, 2, 3], 
 ['A2', 4, 5, 6], 
 ['A3', 7, 8, 9], 
 ['A4', 10, 11, 12]]

3 个答案:

答案 0 :(得分:3)

您可以连接列表:

>>> [[n[0] for n in l]] + [u[1:] for u in l]
[['A', 'B', 'C', 'D'], ['A1', 1, 2, 3], ['A2', 4, 5, 6], ['A3', 7, 8, 9], ['A4', 10, 11, 12]]

答案 1 :(得分:2)

你可以简单地创建另一个列表并加入像这样的结果

print [[n[0] for n in l]] + [u[1:] for u in l]

答案 2 :(得分:1)

喜欢这个吗?

>>> mylist = [[n[0] for n in l]] + [u[1:] for u in l]
>>> mylist
[['A', 'B', 'C', 'D'], ['A1', 1, 2, 3], ['A2', 4, 5, 6], ['A3', 7, 8, 9], ['A4', 10, 11, 12]]