2013-07-24 30 views
1

我有一个输出看起来像这样:蟒蛇发现多个号码之间的距离在列表

output=[[[], [], [], [1582, 2912, 3109, 5711], []], 
[[], [1182, 1432, 2127, 2274, 2613, 3024, 3703, 4723, 5288, 5438], [], []], 
[[], [], [], [], [27, 574, 835, 1221, 1388, 1525, 1842, 2070, 2547, 3578, 3798, 3932, 4066, 4157, 4350, 4567, 4709, 5176, 5564, 5744], [], []], 
[[], [], [], [], []], 
[[]], 
[[], []], 
[[], [1182, 1432, 2127, 2274, 2613, 3024, 3703, 4723, 5288, 5438], [], [], [1452, 2120, 5628]], 
[[3610], []], 
[[], [], [], []], 
[[3842], []], 
[[1566], [3842], []], 
[[5182, 5569], [], []], 
[[], [3842], [], [], [1452, 2120, 5628]], 
[[], [], []], 
[[]], 
[[], [377, 576, 2682, 3071, 5760], [900, 1723, 2658, 3076], []], 
[[], []], 
[[], [], [], [], [1452, 2120, 5628]], 
[[], [1182, 1432, 2127, 2274, 2613, 3024, 3703, 4723, 5288, 5438], [], []]] 

为输出的每一行,我需要找到一个数字的距离的所有可能的组合列表到另一个列表中的数字。例如,对于该行:

[[1566], [3842], []], 

我只需要找到的距离(1566-3842),但该行:

[[], [377, 576, 2682, 3071, 5760], [900, 1723, 2658, 3076], []], 

我需要找到距离的所有可能的组合。有人能告诉我一个快速的方法来做到这一点?非常感谢。

我的想法做这样的:

>>> dis=[] 
>>> for i in range(len(output)): 
    for j in output[i]: 
     if any(abs(num-numb) for num in output[i] for numb in output[i+1]): 
      di=abs(num-numb) 
      dis.append(di) 

我在正确的轨道上?

+0

谢谢,我将编辑帖子。 – user2496006

+0

略好;你可能想要包括你用这种方法遇到的问题,为什么它不起作用。这样我们可以帮助你自己。 –

+0

在描述中,你提到每一行就像是独立的。但在代码中,您似乎在寻找连续行之间的组合。代码是否错误? – RussW

回答

1

有趣的问题,并感谢您的代码片段。我会去一个列表理解,同时也放弃您不需要任何空列表:

在伪代码:

for each line in your output: 
    remove the blank results 
    if there are 2 result sets, 
     then calculate all (x - y) combinations of distances 

在Python:

combinations = [] 
for line in output: 
    result = [i for i in line if i] 
    if len(result) > 1: 
     combinations.append([abs(x - y) for x in result[0] for y in result[1]]) 

combinations.append()使用列表理解(效果和Python一样高效)运行我认为你的计算结果

1

看起来你的行是嵌套的,这意味着一行包含这样的行我有多少个子列表,每个子列表都包含一些距离值或根本没有。它看起来像你想要整行的距离值的所有组合。

在这种情况下,对于任何一行,都可以将列表弄平,然后使用itertools.combinations

如果组合,你的意思是该行中的所有值对所有可能,那么这意味着组合长度由r表示为2

dis = [] 
for row in output: 
    flatrow = sum(row, []) 
    for a, b in itertools.combinations(flatrow, 2): 
     di = abs(a - b) 
     if di: 
      dis.append(di) 
1

你可能寻找itertools.product

from itertools import product 

row = [[], [377, 576, 2682, 3071, 5760], [900, 1723, 2658, 3076], []] 
values = [l for l in row if l] # filter empty lists from the row 
for line in ['{} to {}:\t{}'.format(a, b, abs(a-b)) for (a, b) in product(*values)]: 
    print line 

输出:

377 to 900:  523 
377 to 1723: 1346 
377 to 2658: 2281 
377 to 3076: 2699 
576 to 900:  324 
576 to 1723: 1147 
576 to 2658: 2082 
576 to 3076: 2500 
2682 to 900: 1782 
2682 to 1723: 959 
...