二维列表中的结果第一列表

时间:2019-03-03 06:36:48

标签: python

我有一个二维列表:

list = [[2, 3, 5], [1,2,3], [4,5,6], [8,9,10],[5,6,7]]

我可以使用以下命令打印每个列表的第一个值:

[i[0] for i in list]

结果是:

 list = [2, 1, 4, 8, 5]

但是我想要这样的结果:

list = [[2,3,5],[1,2,3],[4,5,6]]

我的代码是这样的:

new_list = [] 
for i in list:
    row = 1
    row_list = list[row]
    new_list.append(row_list)

有人可以帮助我吗?

4 个答案:

答案 0 :(得分:0)

我有点困惑你在问什么,但是如果我没错,请尝试

print(list[1][1]) #print 2nd element in 2nd subset
print(list[0:3]) #print first 3 elements (in this case subsets) in the list

希望对您有帮助。

要从列表中删除一些对象,可以使用

list.remove(something) #remove element from list

或仅使用

即可创建新列表
l=list[0:3]

答案 1 :(得分:0)

  

但是我想要这样的结果:list = [[2,3,5],[1,2,3],[4,5,6]]

这应该做到:

list_subset = list[:3] # the first 3 elements in the list

答案 2 :(得分:0)

您可以像这样对列表进行切片:

n = 3 # if you have number of items you need
new_list = list[:n]

或:

n = 2 # if you have number of items you want to remove
new_list = list[:-n]

请注意:

  

请勿使用list作为变量的名称,列表是python内置的。

答案 3 :(得分:0)

简单切片可用于跳过最后两行,例如:

list = [[2, 3, 5], [1,2,3], [4,5,6], [8,9,10],[5,6,7]]
print(list[:-2])

[[2, 3, 5], [1, 2, 3], [4, 5, 6]]
相关问题