How to slice middle element from list

不想你离开。 提交于 2019-12-23 08:49:11

问题


Rather simple question. Say I have a list like:

a = [3, 4, 54, 8, 96, 2]

Can I use slicing to leave out an element around the middle of the list to produce something like this?

a[some_slicing]
[3, 4, 8, 96, 2]

were the element 54 was left out. I would've guessed this would do the trick:

a[:2:]

but the result is not what I expected:

[3, 4]

回答1:


You cannot emulate pop with a single slice, since a slice only gives you a single start and end index.

You can, however, use two slices:

>>> a = [3, 4, 54, 8, 96, 2]
>>> a[:2] + a[3:]
[3, 4, 8, 96, 2]

You could wrap this into a function:

>>> def cutout(seq, idx):
        """
        Remove element at `idx` from `seq`.
        TODO: error checks.
        """
        return seq[:idx] + seq[idx + 1:]

>>> cutout([3, 4, 54, 8, 96, 2], 2)
[3, 4, 8, 96, 2]

However, pop will be faster. The list pop function is defined in listobject.c.




回答2:


To remove an item in-place call:

your_list.pop(index)

It will return the removed item and change your_list.




回答3:


Slice the two parts separately and add those lists

a[:2] + a[3:]



回答4:


To work on any size list:

a.pop((len(a)-1)//2)



回答5:


It is the easiest answer:

>>>a = [3, 4, 54, 8, 96, 2]

>>>a.remove(54)

[3, 4, 8, 96, 2]



来源:https://stackoverflow.com/questions/30757538/how-to-slice-middle-element-from-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!