有没有办法在Python中构造惰性序列?

发布于 2024-11-15 18:44:11 字数 693 浏览 4 评论 0原文

有一个 Django 视图,它使用特定的过滤器从数据库加载 Member 对象。

现在,我需要更改此逻辑,以首先呈现特定的成员,然后让其余部分按其自然顺序排列

最直接的方法是立即执行查询,获取列表,在开头删除并插入项目。然而,我很好奇是否还有任何方法可以利用QuerySet的惰性本质

在 C# 中,我会这样写:

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)
);

当循环遍历 members 时,它将首先获取 specificMember,然后使用任何原始的延迟加载逻辑 db.会员使用过

有没有办法在 Django 和 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 lazy loading logic original db.Members used.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

乱世争霸 2024-11-22 18:44:11

使用itertools.chain。类似于:

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

链函数返回一个迭代器。迭代器首先从第一个参数中的序列返回值,该参数是包含 Specific_member 的单元素列表。然后它开始从 original_members 返回值,我认为这是一个惰性序列。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文