son*_*ong 6 python combinations numpy scipy
a = [1, 2, 3, 4, 5, 6]
# OR !
a = ['one', 'two', 'three', 'four', 'five', 'six']
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我只想知道所有可能的组合; 选择ķ间元件一个.如果我使用b = scipy.misc.comb(a, 1),它显示:
b = [1, 2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)
其中b i只是我选择1.如果a是一个字符串数组,它就不起作用.
我真正想要的是:
b = [[1], [2], [3], [4], [5], [6]]
# OR !
b = [['one'], ['two'], ['three'], ['four'], ['five'], ['six']]
Run Code Online (Sandbox Code Playgroud)
这意味着,数组a中元素中可能的1个选定元素的集合
如果我使用MATLAB,这很容易.但我正在尝试使用SciPy堆栈.
使用scipy而不是itertools这个特定问题的任何理由?
调查itertools.combinations或itertools.permutations可能提供更充分的解决方案.
这是一个更完整的答案.你应该使用itertools.combinations而不是itertools.permutations因为组合与排列有很大的不同.
例如,如果您需要数组的所有两个元素组合(例如[1,2,3,5]以下代码)将生成您想要的结果(相当于nchoosekMatlab中的结果).查看此来源的更多示例.
>>> import itertools
>>> all_combos = list(itertools.combinations([1,2,3,5], 2))
>>> print all_combos
[(1, 2), (1, 3), (1, 5), (2, 3), (2, 5), (3, 5)]
Run Code Online (Sandbox Code Playgroud)
如果您希望所有组合作为2d数组,只需使用以下命令将元组列表转换为numpy数组:
>>> all_combos = np.array(list(itertools.combinations([1,2,3,5], 2)))
>>> print all_combos
[[1 2]
[1 3]
[1 5]
[2 3]
[2 5]
[3 5]]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3320 次 |
| 最近记录: |