Joh*_*y_M 4 python combinations python-itertools python-3.x
>>> import itertools
>>> n = [1,2,3,4]
>>> combObj = itertools.combinations(n,3)
>>>
>>> combObj
<itertools.combinations object at 0x00000000028C91D8>
>>>
>>> list(combObj)
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
>>>
>>> for i in list(combObj): #This prints nothing
... print(i)
...
Run Code Online (Sandbox Code Playgroud)
我怎样才能遍历combObj?
我怎样才能转换
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
为
[[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]
一旦遍历itertools.combinations对象一次,它就会被用完,你不能再次迭代它.
如果你需要重复使用它,正确的方法是使它成为一个list或tuple像你一样.你需要做的就是给它一个名字(把它分配给一个变量),这样就可以了.
combList = list(combObject) # Don't iterate over it before you do this!
Run Code Online (Sandbox Code Playgroud)
如果你只想迭代它一次,你根本就不要打list它:
for i in combObj: # Don't call `list` on it before you do this!
print(i)
Run Code Online (Sandbox Code Playgroud)
旁注:命名对象实例/正常变量的标准方法comb_obj不是combObj.有关详细信息,请参阅PEP-8.
要将内部tuples 转换为lists,请使用列表推导和list()内置:
comb_list = [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
comb_list = [list(item) for item in comb_list]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1965 次 |
| 最近记录: |