简体   繁体   中英

Removing elements from list

I have an array of length 900 and I want to remove the last 200 elements. I do not mind creating a new array but I want to code to be an concise and efficient as possible.

    f = [1,2,3,4,5,3,2,3,2,4,5,2....] #random one digit numbers of length 400. 
    t=400
    x=200
    while(t>x):
        f = np.delete(f,t)
        t = t-1

while this certainly works, I am looking for something that will preform the same task in less lines or at greater speed.

You can use list slicing:

f = [1,2,3,4,5,3,2,3,2,4,5,2....]

f = f[:-200]

您也可以删除元素而不创建新列表:

del f[-200:]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM