根据单个值生成一系列数字(坐标)

时间:2019-05-16 07:52:08

标签: python-3.x python-2.7 loops

我想按以下模式生成数字: 初始坐标为: models.py from django.db import models # Create your models here. class BookManager(models.Manager): def title_count(self, keyword): return self.filter(title__icontains=keyword).count() class Book(models.Model): title = models.CharField(max_length=100) publication_date = models.DateField() page_length = models.IntegerField(null=True, blank=True) objects = BookManager() def __unicode__(self): return self.title views.py from django.shortcuts import render from django.views.generic import ListView from .models import Book class BookViewPage(ListView): model = Book title_number = Book.objects.title_count('django') def bookviewpage(request): context ={ 'count': Book.objects.title_count('django') } return render(request, 'books/book_list.html', context)

(a,b)=(2,3)

对于下一次迭代,(c,d) must be generate by (a+2,b+2) i.e. (4,5) (e,f) must be generate by (a+2,b) i.e (4,3) 将是上一步的a and b: 即c and d 像这样

。有人能给我循环逻辑来生成这种坐标/数字模式吗?

1 个答案:

答案 0 :(得分:2)

您可以使用生成器(根据您的描述进行翻译):

def pattern(a, b):
    yield (a, b)
    while True:
        c, d = (a+2, b+2)
        e, f = (a+2, b)
        yield (c, d)
        yield (e, f)
        a, b = (c, d)

例如:

>>> def pattern(a, b):
...     yield (a, b)
...     while True:
...         c, d = (a+2, b+2)
...         e, f = (a+2, b)
...         yield (c, d)
...         yield (e, f)
...         a, b = (c, d)
... 
>>> g =  pattern(2, 3)
>>> [next(g) for _ in range(10)]
[(2, 3), (4, 5), (4, 3), (6, 7), (6, 5), (8, 9), (8, 7), (10, 11), (10, 9), (12, 13)]