Python 二维列表中的结果第一个列表
我有一个这样的二维列表:Python 二维列表中的结果第一个列表,python,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 = [[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)
有人能帮我吗?我有点不明白你在问什么,但如果我答对了,我就试试看
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]
但我想得到这样的结果:list=[[2,3,5],[1,2,3],[4,5,6]]
这应该做到:
list_subset = list[:3] # the first 3 elements in the list
您可以按如下方式分割列表:
n = 3 # if you have number of items you need
new_list = list[:n]
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]]
或:
请注意:
不要使用list
作为变量名,list是python中内置的
简单切片可用于跳过最后两行,如下所示:
n = 3 # if you have number of items you need
new_list = list[:n]
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]]
在什么样的逻辑上,您想要的结果是
list=[[2,3,5],[1,2,3],[4,5,6]
。为什么剩下的两个子列表不在结果中?@michaelpetronav因为我不需要剩下的两个子列表