python:如何在不重复项目的情况下制作可迭代的产品?

发布于 2024-11-12 19:55:47 字数 1249 浏览 2 评论 0原文

我需要一个功能与 itertools.product 类似的函数,但不重复项目。

例如:

no_repeat_product((1,2,3), (5,6))
= ((1,5), (None,6), (2,5), (None,6), ...(None,6))
no_repeat_product((1,2,3), (5,6), (7,8))
= ((1,5,7), (None,None,8), (None,6,7), (None,None,8), ...(None,None,8))

有什么想法吗?

编辑: 我的措辞不正确。我的意思是不重复连续输出值中相同的数字
例如,

itertools.product((1,2,3), (4,5), (6,7) is
(1,4,6)
(1,4,7), etc  

Here 1,4 在输出中出现两次。所以,当数字与之前的项目相同时,我想跳过写数字。所以,我想要的输出是:

(1,4,6)  
(None,None,7)  

当它为 None 时,可以理解它与结果中的前一项相同。

进一步编辑:

我的解释仍然不够清晰。 假设我有书籍列表、章节号和页码。假设每本书的章节数相同,并且每章的页数相同。 因此,列表为 (book1, book2, book3), (chap1, chap2), (page1, page2, page3)。
现在,假设我想收集每个页面的描述:
itertools.product 会给我:

(book1, chap1, page1), (book1, chap1, page2)..... (book3, chap2, page3)

如果我连续排列这些页面,我不需要重复描述。因此,如果书籍和章节相同,那么在第二页中,我不需要书籍和章节名称 所以,输出应该是:

(book1, chap1, page1), (None, None, page2), ..   
(when the pages of first chapter are over..) (None, chap2, page1), (None, None, page2)......  
(when the chapters of the first book are over..)(book2, chap1, page1)..............  
(None, None, page3)  

I need a function that functions in a similar manner as itertools.product, but without repeating items.

For example:

no_repeat_product((1,2,3), (5,6))
= ((1,5), (None,6), (2,5), (None,6), ...(None,6))
no_repeat_product((1,2,3), (5,6), (7,8))
= ((1,5,7), (None,None,8), (None,6,7), (None,None,8), ...(None,None,8))

Any ideas?

Edit:
my wording was not correct. I meant without repeating the numbers that are same in successive output values.
For example,

itertools.product((1,2,3), (4,5), (6,7) is
(1,4,6)
(1,4,7), etc  

Here 1,4 appears twice in the output. So, I want to skip writing the numbers when they are the same as the item before. So, the output I want is:

(1,4,6)  
(None,None,7)  

When it is None, it is understood that it is same as its previous item in the result.

Further Edit:

My explanation was still lacking in clarity.
Let us assume that I have list of books, chapter numbers, and page numbers. Assume that each book has same number of chapters and each chapter has same number of pages.
So, the lists are (book1, book2, book3), (chap1, chap2), (page1, page2, page3).
Now, suppose I want to collect descriptions for each page:
itertools.product will give me:

(book1, chap1, page1), (book1, chap1, page2)..... (book3, chap2, page3)

If I have arranged these pages successively, I do not need to have descriptions repeating. So, if the book and the chapter are the same, in the second page, I don't need to have book and chapter names
So, the output should be:

(book1, chap1, page1), (None, None, page2), ..   
(when the pages of first chapter are over..) (None, chap2, page1), (None, None, page2)......  
(when the chapters of the first book are over..)(book2, chap1, page1)..............  
(None, None, page3)  

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

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

发布评论

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

评论(3

记忆で 2024-11-19 19:55:47

根据您的评论“因为 (None,None,8) 不会连续发生”,我假设您只想 None-ify 中出现的元素之前输出。

def no_repeat_product(*seq):
    previous = (None,)*len(seq)
    for vals in itertools.product(*seq):
        out = list(vals)
        for i,x in enumerate(out):
            if previous[i] == x:
                out[i] = None
        previous = vals
        yield(tuple(out))   

或者,如果您更喜欢更紧凑、更高效(但可读性较差)的版本:

def no_repeat_product(*seq):
    previous = (None,)*len(seq)
    for vals in itertools.product(*seq):
        out = tuple((y,None)[x==y] for x,y in itertools.izip(previous, vals))
        previous = vals
        yield(out)       

它们都执行相同的操作,并产生以下结果:

for x in no_repeat_product((1,2,3), (5,6), (7,8)): 
    print x 

输出:

(1, 5, 7)
(None, None, 8)
(None, 6, 7)
(None, None, 8)
(2, 5, 7)
(None, None, 8)
(None, 6, 7)
(None, None, 8)
(3, 5, 7)
(None, None, 8)
(None, 6, 7)
(None, None, 8)

对于更新问题的上下文中的示例:

books = ("Book 1", "Book 2")
chapters = ("Chapter 1", "Chapter 2")
pages = ("Page 1", "Page 2", "Page 3")

s1 = max(map(len, books)) + 2  # size of col 1
s2 = max(map(len, chapters)) + 2  # size of col 2
x = lambda s, L: (s, "")[s == None].ljust(L)  # Left justify, handle None

for book, chapter, page in no_repeat_product(books, chapters, pages):
    print x(book, s1), x(chapter, s2), page

这为您提供:

Book 1   Chapter 1   Page 1
                     Page 2
                     Page 3
         Chapter 2   Page 1
                     Page 2
                     Page 3
Book 2   Chapter 1   Page 1
                     Page 2
                     Page 3
         Chapter 2   Page 1
                     Page 2
                     Page 3

Based on your comment stating "because (None,None,8) does not occur successively", I'm assuming you only want to None-ify elements that appear in the output immediately before.

def no_repeat_product(*seq):
    previous = (None,)*len(seq)
    for vals in itertools.product(*seq):
        out = list(vals)
        for i,x in enumerate(out):
            if previous[i] == x:
                out[i] = None
        previous = vals
        yield(tuple(out))   

Or, if your prefer a more compact and efficient (but less readable) version:

def no_repeat_product(*seq):
    previous = (None,)*len(seq)
    for vals in itertools.product(*seq):
        out = tuple((y,None)[x==y] for x,y in itertools.izip(previous, vals))
        previous = vals
        yield(out)       

They both do the same thing, and produces the following results:

for x in no_repeat_product((1,2,3), (5,6), (7,8)): 
    print x 

Output:

(1, 5, 7)
(None, None, 8)
(None, 6, 7)
(None, None, 8)
(2, 5, 7)
(None, None, 8)
(None, 6, 7)
(None, None, 8)
(3, 5, 7)
(None, None, 8)
(None, 6, 7)
(None, None, 8)

For an example in the context of your updated question:

books = ("Book 1", "Book 2")
chapters = ("Chapter 1", "Chapter 2")
pages = ("Page 1", "Page 2", "Page 3")

s1 = max(map(len, books)) + 2  # size of col 1
s2 = max(map(len, chapters)) + 2  # size of col 2
x = lambda s, L: (s, "")[s == None].ljust(L)  # Left justify, handle None

for book, chapter, page in no_repeat_product(books, chapters, pages):
    print x(book, s1), x(chapter, s2), page

This gives you:

Book 1   Chapter 1   Page 1
                     Page 2
                     Page 3
         Chapter 2   Page 1
                     Page 2
                     Page 3
Book 2   Chapter 1   Page 1
                     Page 2
                     Page 3
         Chapter 2   Page 1
                     Page 2
                     Page 3
顾北清歌寒 2024-11-19 19:55:47
def no_repeat_product(*seq):
    def no_repeat(x, known):
        if x in known:
            return None
        else:
            known.add(x)
            return x

    known = set()
    for vals in itertools.product(*seq):
        yield tuple(no_repeat(x, known) for x in vals)

这不会返回之前已经见过的任何值。这是你想要的吗?

如果您只想限制上一组结果中出现的值的重复,可以这样做:

def no_repeat_product(*seq):
    prev = None
    for vals in itertools.product(*seq):
        if prev is None:
            yield vals
        else:
            yield tuple((x if x != y else None) for x, y in zip(vals, prev))
        prev = vals
def no_repeat_product(*seq):
    def no_repeat(x, known):
        if x in known:
            return None
        else:
            known.add(x)
            return x

    known = set()
    for vals in itertools.product(*seq):
        yield tuple(no_repeat(x, known) for x in vals)

This doesn't return any value that has already been seen before. Is this what you want?

If you only want to limit repetition of a value that appeared in the previous set of results, it can be done this way:

def no_repeat_product(*seq):
    prev = None
    for vals in itertools.product(*seq):
        if prev is None:
            yield vals
        else:
            yield tuple((x if x != y else None) for x, y in zip(vals, prev))
        prev = vals
梦幻之岛 2024-11-19 19:55:47

有点像 @ShawnChin 的答案的功能版本,使用 tee'ed 迭代器:

from itertools import product,tee,izip
def product_without_repeats(*seq):
    previter,curriter = tee(product(*seq))
    try:
        yield next(curriter)
    except StopIteration:
        pass
    else:
        for prev,curr in izip(previter,curriter):
            yield tuple(y if x!=y else None for x,y in izip(prev,curr))

Sort of a functional version of @ShawnChin's answer, using a tee'ed iterator:

from itertools import product,tee,izip
def product_without_repeats(*seq):
    previter,curriter = tee(product(*seq))
    try:
        yield next(curriter)
    except StopIteration:
        pass
    else:
        for prev,curr in izip(previter,curriter):
            yield tuple(y if x!=y else None for x,y in izip(prev,curr))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文