在列表之间获得独特的产品并维护inpu的秩序

2024-05-14 06:27:51 发布

您现在位置:Python中文网/ 问答频道 /正文

关于列表的唯一(笛卡尔)积有很多问题,但是我在寻找一些我在其他问题中没有发现的奇怪的东西。你知道吗

我的输入总是由两个列表组成。当列表是相同的,我想得到所有的组合,但当他们是不同的,我需要唯一的产品(即顺序不重要)。然而,除此之外,我还需要保留顺序,因为输入列表的顺序很重要。实际上,我需要的是,第一个列表中的项应该始终是产品元组的第一个项。你知道吗

我有下面的工作代码,这正是我想要的除了我没有找到一个好的,有效的方法来保持项目的顺序如上所述。你知道吗

import itertools

xs = ['w']
ys = ['a', 'b', 'c']

def get_up(x_in, y_in):
    if x_in == y_in:
        return itertools.combinations(x_in, 2)
    else:
        ups = []
        for x in x_in:
            for y in y_in:
              if x == y:
                  continue
              # sort so that cases such as (a,b) (b,a) get filtered by set later on
              ups.append(sorted((x, y)))
        ups = set(tuple(up) for up in ups)
        return ups

print(list(get_up(xs, ys)))
# [('c', 'w'), ('b', 'w'), ('a', 'w')]

如您所见,结果是按字母顺序排列的唯一元组列表。我使用排序,这样我就可以通过使用一个集合来过滤重复的条目。但是因为第一个列表(xs)包含w,所以我希望元组将该w作为第一项。你知道吗

[('w', 'c'), ('w', 'b'), ('w', 'a')]

如果两个列表之间存在重叠,那么两个列表中出现的项的顺序就无关紧要了,因此对于xs = ['w', 'a', 'b']ys = ['a', 'b', 'c']来说,a的顺序就无关紧要了

[('w', 'c'), ('w', 'b'), ('w', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'c')]
                                         ^

或者

[('w', 'c'), ('w', 'b'), ('w', 'a'), ('a', 'c'), ('b', 'a'), ('b', 'c')]
                                                     ^

最好是以一个生成器结束(正如combinations返回的那样)。我也只对Python>;=3.6感兴趣。你知道吗


Tags: in列表forgetreturnif顺序产品
2条回答

以保持顺序的方式收集元组(当列表相同时),然后通过移除逆元组进行过滤。你知道吗

if x_in == y_in:
        return itertools.combinations(x_in, 2) 
    else:
        seen = set()
        for a,b in itertools.product(x_in, y_in):
            if a == b or (b, a) in seen:
                continue
            else:
                yield (a,b)
                seen.add((a,b))

这将为您提供(x, y)顺序的元组;当(a,b)(b,a)同时出现时,您将只获得最先看到的顺序。你知道吗

我会回答我自己的问题,不过我敢打赌使用itertools或其他工具会有更好的解决方案。你知道吗

xs = ['c', 'b']
ys = ['a', 'b', 'c']


def get_unique_combinations(x_in, y_in):
    """ get unique combinations that maintain order, i.e. x is before y """
    yielded = set()
    for x in x_in:
        for y in y_in:
            if x == y or (x, y) in yielded or (y, x) in yielded:
                continue

            yield x, y
            yielded.add((x, y))

    return None

print(list(get_unique_combinations(xs, ys)))

相关问题 更多 >