python - 元素类型组合的解决方案,当任何类型都可以有零个元素时
问题描述
我有 3 个模型/实体,A、B、C(后端是 django)。
在前端我有 3 个空框,我需要在其中添加 A、B、C 的实例。A、B、C 的可用实例数可以是 0 到无限。
理想情况下,我应该显示 A 的 1 个、B 的 1 个和 C 的 1 个,但有时任何实体都可以没有实例。可以是无、一个或多个,没有实例。
我的基本方法是使用ifs
,但效率不高,请仅查看伪代码中的一个分支:
if not C:
if A:
if not B:
show up to 3 of A if they are available
elif B:
if at least 2 of A:
show 2 of A and 1 Of B
if 1 of A:
show 1 of A and up to 2 of B
elif not A:
show up to 3 of B if exist
除了ifs
在所有分支上都有几十个之外,它不会扩展,例如,如果我将来添加一个新的实体和/或框。
所以,我正在寻找一种可以扩展的算法。我正在使用 Python、django、PostgreSQL。我提取数据,简单:
A.objects.all().order_by('-id')[:3]
解决方案
models = [A, B, C]
num_boxes = len(models) # but could be different
objects = [list(model.objects.all().order_by('-id')[:num_boxes])
for model in models]
boxes = []
while any(objects):
for row in objects:
if row:
boxes.append(row.pop(0))
print(sorted(
boxes[:num_boxes],
key=lambda x: models.index(type(x))
))
推荐阅读
- docker - 在 Docker 容器中运行我的应用程序
- macos-catalina - 如何为 Mac OS catalina 编写驱动程序包扩展
- c++ - android和windows应用程序之间的TCP Socket连接
- arrays - BASH 数组的单个下标中是否可以有多个值?
- lua - 如何在另一个表中的另一个表中插入另一个表?
- c# - C#总结列表中的多个项目
- android - 来自数据库的 LiveData 不会触发 Transformations.switchMap
- karate - 上传文件时出错","错误":["分配前引用的局部变量 'upload_file_path'" - 在空手道中使用 ".yaml" 文件的发布方法
- xml - 如何为此 XML 文件编写 XSLT 文件
- python - 如何使用 python 更新 Elastic Search ( Kibana ) 中可用的大量 Json 数据