我有一个类似的列表:
\.([^\\.]*\.[^\\.]*)$
我需要将子列表中的每个元素与每个其他元素(自身除外)配对。期望的输出:
results=[['000', '111', '000'],
['110', '000', '101'],
['000', '000', '000']]
尝试的代码:
[[['000', '111'], ['000', '000'], ['111', '000']],
[['110', '000'], ['110', '101'], ['000', '101']],
[['000', '000'], ['000', '000'], ['000', '000']]]
我不太确定我哪里出错了。指数和范围工作正常,有什么建议吗?
答案 0 :(得分:2)
在我看来,您希望您的子列表中的每个组合都有2个。使用itertools
:
>>> import itertools
>>> results=[['000', '111', '000'], ['110', '000', '101'], ['000', '000', '000']]
>>> [[list(comb) for comb in itertools.combinations(sub,2)] for sub in results]
[[['000', '111'], ['000', '000'], ['111', '000']], [['110', '000'], ['110', '101'], ['000', '101']], [['000', '000'], ['000', '000'], ['000', '000']]]
使用漂亮的印刷品来说清楚:
>>> from pprint import pprint
>>> combos = [[list(comb) for comb in itertools.combinations(sub,2)] for sub in results]
>>> pprint(combos)
[[['000', '111'], ['000', '000'], ['111', '000']],
[['110', '000'], ['110', '101'], ['000', '101']],
[['000', '000'], ['000', '000'], ['000', '000']]]
>>>
答案 1 :(得分:0)
这是一种列表理解方式:
[ [ [ [L[i],L[j]] for i in range(j) ] for j in range(1,len(L))] for L in results]