Python -itertools模块combinations方法
生活随笔
收集整理的這篇文章主要介紹了
Python -itertools模块combinations方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
itertools模塊combinations(iterable, r)方法可以創建一個迭代器,返回iterable中所有長度為r的子序列,返回的子序列中的項按輸入iterable中的順序排序。
例1:
from itertools import combinations li = [1,2,3,4] newIter = combinations(li,2) print(newIter) newList = list(newIter) print(newList)輸出:
<itertools.combinations object at 0x000002721AEB6C70> [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]例2、實現一位數組的所有排列組合:
''' 學習中遇到問題沒人解答?小編創建了一個Python學習交流QQ群:531509025 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' from itertools import combinations li = [1,2,3,4] li2 = [] for i in range(1,len(li)+1):newLi = list(combinations(li,i))li2.append(newLi) print(li2)輸出:
[[(1,), (2,), (3,), (4,)], [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)], [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)], [(1, 2, 3, 4)]]例3:利用chain.from_iterable方法將多個迭代器連接起來
from itertools import combinations,chain li = [1,2,3,4] print(list(chain.from_iterable(combinations(li,r) for r in range(len(li)+1))))輸出:
[(), (1,), (2,), (3,), (4,), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4), (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4), (1, 2, 3, 4)]結尾給大家推薦一個非常好的學習教程,希望對你學習Python有幫助!
Python基礎入門教程推薦:更多Python視頻教程-關注B站:Python學習者
【Python教程】全網最容易聽懂的1000集python系統學習教程(答疑在最后四期,滿滿干貨)
Python爬蟲案例教程推薦:更多Python視頻教程-關注B站:Python學習者
2021年Python最新最全100個爬蟲完整案例教程,數據分析,數據可視化,記得收藏哦
總結
以上是生活随笔為你收集整理的Python -itertools模块combinations方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python中defaultdict函数
- 下一篇: python中的any与all函数的区别