列表中重叠对的Python组合

Cha*_*guy 1 python combinations hadoop

我正在运行一个Python脚本作为Hadoop流媒体工作,但这篇文章与一些核心Python概念有关,而不是关于Hadoop的知识.

基本上我有一组行,我想找到重叠

$ cat sample.txt
ID1    2143,2154,
ID2    2913,14545
ID3    2143,2390,3350,5239,6250
ID4    2143,2154,2163,3340
ID5    2143,2154,2156,2163,3340,3711
Run Code Online (Sandbox Code Playgroud)

我想最终找到重叠的记录对并计算它们,例如:

2143,2154    3
2143,2163    2
2143,3340    2
2154,2163    2
2154,3340    2
2163,3340    2
Run Code Online (Sandbox Code Playgroud)

我这样做的方法是创建一个用Python编写的Hadoop流作业,其中mapper将基本输出给定行上的所有对组合,这将由reducer进一步处理.

我的问题实际上非常简单:如何在Python中有效地生成给定行中所有对的组合?请注意,在我的情况下,一对(x,y)与一对(y,x)相同.例如,ID3我想在我的映射器中生成以下列表:

[(2143,2390), (2143,2390), (2143,3350), (2143,5239), (2143,6250), (2390,3350), (2390,5239), (2390,6250), (3350,5239), (3350,6250), (5239,6250)]
Run Code Online (Sandbox Code Playgroud)

我当然可以通过一堆for循环来做到这一点,但它非常难看.我尝试过使用itertools,却无法正确使用它.有什么想法吗?

tom*_*m10 8

怎么样:

x = [2143, 2390, 3350, 5239, 6250]
itertools.combinations(x, 2)
Run Code Online (Sandbox Code Playgroud)

得到:

(2143, 2390) (2143, 3350) (2143, 5239) (2143, 6250) (2390, 3350) (2390, 5239) (2390, 6250) (3350, 5239) (3350, 6250) (5239, 6250)
Run Code Online (Sandbox Code Playgroud)

  • (+1)我认为这是最好的解决方案. (2认同)
  • +1,但你需要先对它进行排序,即`组合(sorted(x)` (2认同)