在python中使用组合对象

>>> 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)
...

>我如何遍历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对象,它就会被用完,你不能再次迭代它.

如果您需要重用它,正确的方法是将其作为列表或元组.你需要做的就是给它一个名字(把它分配给一个变量),这样就可以了.

combList = list(combObject) # Don't iterate over it before you do this!

如果你只想迭代它一次,你根本就不要在它上面调用list:

for i in combObj: # Don't call `list` on it before you do this!
    print(i)

旁注:命名对象实例/正常变量的标准方法是comb_obj而不是combObj.有关详细信息,请参阅PEP-8.

要将内部元组转换为列表,请使用列表推导和内置的list():

comb_list = [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
comb_list = [list(item) for item in comb_list]
上一篇:在Python中反复使用计数器创建文件


下一篇:Itertools.count Python