假設我們有一個 list L = ['a', 'b', 'c'],我想執行一組采樣L以生成預期結果:
[['a'], ['b'], ['c'], ['a', 'b'], ['a', 'c'], ['b', 'c'], ['a', 'b', 'c']]
我們可以看到,在這個最終輸出中,一個串列串列,它的每個元素,沒有考慮順序的重復元素。如何在 Python 中實作它?
uj5u.com熱心網友回復:
一種方法是使用combinationsfromitertools模塊。r=在 for 回圈中執行此操作并每次更改其引數。r=1, r=2, 直到r=len(L):
from itertools import combinations
lst = ["a", "b", "c"]
print([list(item) for i in range(1, len(lst) 1) for item in combinations(lst, i)])
輸出:
[['a'], ['b'], ['c'], ['a', 'b'], ['a', 'c'], ['b', 'c'], ['a', 'b', 'c']]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/527069.html
