Python删除多维数组中的项

2024-09-27 09:32:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个多维数组:

[["asdf","bmnl", "123","456,"0","999","1234","3456"],["qwer","tyui","789","657,"122","9","673","1"]]

但是,在多维数组中,只需要每个数组的最后6项,而不需要前两项。如何从多维数组中的每个数组中删除前两段数据,使其看起来像:

^{pr2}$

到目前为止,我已经做到了:

list1 = []
list2 = []
for row in rows:
    list1.append(row[0].split(',')) #to put the split list into the top i i.e. [["asdf","bmnl", "123","456,"0","999","1234","3456"]["qwer","tyui","789","657,"122","9","673","1"]]
for i in list1:
    for index in len(list1):
        if index >=2:
             list2.append(index) #this does not work and causes errors

我如何着手解决这个问题,以便输出:

^{pr2}$

谢谢


Tags: theinforindex数组rowsplitappend
3条回答
lst = [["asdf","bmnl", "123","456","0","999","1234","3456"],["qwer","tyui","789","657","122","9","673","1"]]
for i in lst:
    del i[0:2] #deleting 0 and 1 index from each list

print lst

只需使用列表理解并从索引2以及每个子列表中的其他元素中获取每个元素:

>>> array = [["asdf","bmnl", "123","456","0","999","1234","3456"],["qwer","tyui","789","657","122","9","673","1"]]
>>> [sublist[2:] for sublist in array]
[['123', '456', '0', '999', '1234', '3456'], ['789', '657', '122', '9', '673', '1']]

这是list comprehension的典型用例:

list2 = [item[2:] for item in list1]

相关问题 更多 >

    热门问题