开发者

Is there a way to construct lazy sequences in Python?

There is a Django view that loads Member objects from the database with a certain filter.

Now I need to change this logic to present a specific Member first, and let the rest follow in their natural order.

The most straightforward way is to execute the query right away, get a list, remove and insert the item at the beginning. However I am most curious if there is still any way to make use of QuerySet's lazy nature.

In C#, I would write:

IEnumerable<Member> members = db.Members; // db.Members is lazy
members = Enumerable.Union( // construct a lazy sequence that traverses its arguments
    new [] { specificMember },
    members.Where(m => m != specificMember)
);

As a loop would go through members, it would first get specificMember and then use whatever laz开发者_运维百科y loading logic original db.Members used.

Is there a way to do the same in Django and Python?


Use itertools.chain. Something like:

import itertools
original_members = .... # get an iterator of the data
members = itertools.chain([specific_member], original_members)

The chain function returns an iterator. The iterator starts by returning the value from the sequence in the first parameter, which is a single-element list containing specific_member. Then it starts returning the values from original_members, which I assume is a lazy sequence.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜