浏览数组python的每个可能组合

时间:2016-05-13 20:57:54

标签: python arrays combinations

假设您有4个数字的数组。通过所有可能组合的最佳方法是什么?组合的开始是:

1,2,3,4

1,2,4,3

1,3,2,4-

1,3,4,2

1,4,2,3

2,1,3,4

2 个答案:

答案 0 :(得分:2)

itertools.permutations正是您所寻找的:

219     updateMonitorSelectors: function () {
220         //p.ex.currentReload.monitor.selectors.length = 0;
221         if (p.v.isInitSelector) return;
222         p.ex.currentReload.monitor.selectors = [];
223         $(p.s.dMonitor_nu + ' input[type="text"]').each(function () {
224             var disabled = $(this).attr('disabled');
225             if (!disabled) {
226                 p.ex.currentReload.monitor.selectors[p.ex.currentReload.moni    tor.selectors.length] = $(this).val();
227             }
228         });
229     },
230     initControls: function () {
231         if (this.initControls.timerId) clearTimeout(this.initControls.timerI    d);
232         if (p.ex.currentReload === null) { this.initControls.timerId = setTi    meout('p.initControls()', 250); return; };
233         var reload = p.ex.currentReload;
234         $(p.s.tRandomStartSecs).val(reload.rand.from);
235         $(p.s.tRandomEndMins).val(reload.rand.to / 60);
236         $(p.s.tCustomSecs).val(reload.secs);
237         $(p.s.tDefaultSecs).val(p.ex.defaultTime);
238         if (reload.isTabRefresh) { $(p.s.rTab).attr('checked', 'checked'); }
239         else $(p.s.rUrl).attr('checked', 'checked');
240
241         if (reload.span.isStartOn) {
242             $(p.s.cStart).attr('checked', 'checked');
243             $(p.s.tStart).removeAttr('disabled');
244             $(p.s.tStart).val(p.time.toLocal(reload.span.startTime));
245         }
246         if (reload.span.isEndOn) {
247             $(p.s.cEnd).attr('checked', 'checked');
248             $(p.s.tEnd).removeAttr('disabled');
249             $(p.s.tEnd).val(p.time.toLocal(reload.span.endTime));
250         }
251

修改
或者,正如@wflynny指出的那样,只需调用>>> from itertools import permutations >>> [i for i in permutations(range(1, 5), 4)] [(1, 2, 3, 4), (1, 2, 4, 3), (1, 3, 2, 4), (1, 3, 4, 2), (1, 4, 2, 3), (1, 4, 3, 2), (2, 1, 3, 4), (2, 1, 4, 3), (2, 3, 1, 4), (2, 3, 4, 1), (2, 4, 1, 3), (2, 4, 3, 1), (3, 1, 2, 4), (3, 1, 4, 2), (3, 2, 1, 4), (3, 2, 4, 1), (3, 4, 1, 2), (3, 4, 2, 1), (4, 1, 2, 3), (4, 1, 3, 2), (4, 2, 1, 3), (4, 2, 3, 1), (4, 3, 1, 2), (4, 3, 2, 1)] 的构造函数即可保存列表解析:

list

答案 1 :(得分:0)

您可以使用itertools模块:

import itertools
arr = [1,2,3,4]
print [x for x in itertools.permutations(arr)]