简体   繁体   中英

Python: How to get first 5 or last 5 from list of 10?

Below searches is a list of objects (10). Instead of hitting the database again and this time doing (5) to get put 5 in another variable. How would I write it below to check the variable searches to get 10 from that?

searches = self.get_recent_searches(10)
dic['recents'] = searches ## 10 objects
##dic['recent'] = self.get_recent_searches(5)
dic['recent'] = searches.get 5 from this list

searches:

在此处输入图片说明

It looks like searches is a dictionary, so you may need to deference one more time ie

searchdict = self.get_recent_searches(10)
searches = searchdict['searches']

dic['recent'] = searches[:5]

要获取前五项,可以使用searches[:5] ,该searches[:5]开始并转到(但不包括)元素5。要获取后五项,可以使用searches[-5:] ,其中从项目-5(从末尾转换为第五个项目)开始,然后到列表的末尾。

If I understand right, you could use slice, like :

dic['recents'] = searches[:10]

The slice is used to get part of the list, in form of :

content[begin : end]

Python list is zero index based. And begin(th) element is included in the result, while the end(th) element is exlusive. If you want to first i elements, please use searches[:i]. If the last i elements are needed, searches[-i:] works well.

Hope it be helpful!

To get the first or last 5 out of your list you can use list comprehension. See below:

my_list = [1,2,3,4,5,6,7,8,9,10]

#puts first 5 elements in new list
first_five = [x for x in my_list[0:5]]
print first_five

#puts elements after index 5 into new list
last_five = [x for x in my_list[5:]]
print last_five

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