假设我们有一个像a = [['a','b','c'], ['aber', 'jsfn', 'ff', 'fsf', '003'], [...] ...]这样的数组,其中每个元素可以有不同的大小。我想要做的是删除每个子数组的最后一项,如果它符合我设置的条件。所以我有:
for x in range(len(a)):
if the last item in x matches some condition that is set:
then remove the last item from x因为我处理的是一个数组,所以我尝试了a.remove(-1),但这是错误的。那么,有什么简单的方法可以做到这一点吗?
举个例子,如果我有:
for x in range(len(a)):
if the last element of each sub-array starts with an "S":
then remove the last item from that sub-array我该如何处理这个问题呢?任何例子或一些教程的链接都是非常感谢的。
发布于 2015-02-04 01:42:59
Python按索引列出了support del:
>>> l = [1,2]
>>> del l[-1]
[1].remove(值)删除第一个匹配值。
.pop(值)与remove相同,但它返回被移除的值,如果你不给它赋值,它将“弹出”列表中的最后一项。
发布于 2015-02-04 01:44:49
你在这里看到的是一个列表,而不是一个数组。在此基础上,您可以执行以下操作:
a = [['a','b','c'], ['aber', 'jsfn', 'ff', 'fsf', '003'], ['d', 'Starts With S']]
for sublist in a:
if sublist[-1].startswith("S"):
sublist.pop()
print a它在运行时会产生:
[['a', 'b', 'c'], ['aber', 'jsfn', 'ff', 'fsf', '003'], ['d']]发布于 2015-02-04 01:41:10
您可以将要删除的元素传递给remove(),或者如果您只想删除最后一个元素,请使用pop(),请参阅以下示例:
>>> a = [['a','b','c'], ['aber', 'jsfn', 'ff', 'fsf', '003']]
>>> a[0].remove(a[0][1]) # a[0][1] is 'b'
>>> a[0]
['a', 'c']
>>> a
[['a', 'c'], ['aber', 'jsfn', 'ff', 'fsf', '003']]
>>> a[1].pop() # remove the last element of a[1]
'003'
>>> a
[['a', 'c'], ['aber', 'jsfn', 'ff', 'fsf']]https://stackoverflow.com/questions/28305253
复制相似问题