![](/img/trans.png)
[英]In Python, fastest way to create all possible combinations of replacing up to N positions in a list with a character
[英]Python compute all possible positions of n items in a list
我正在嘗試顯示組合列表,但我無法使這個 function 可用於所有 n 的。 例如,在 k 個位置上 position n 1 有多少種方式。
這就是我試圖做的。 在這種情況下 n = 2 和 k = 6
def ff():
x_list = []
for i in range(6):
for j in range(6)[i+1::]:
new_list = [0 for x in range(6)]
new_list[i] = 1
new_list[j] = 1
x_list.append(new_list)
return x_list
ff()
例如對於 n = 3
def ff():
x_list = []
for i in range(6):
for j in range(6)[i+1::]:
for k in range(6)[j+1::]:
new_list = [0 for x in range(6)]
new_list[i] = 1
new_list[j] = 1
new_list[k] = 1
x_list.append(new_list)
return x_list
ff()
但是我顯然不想重寫相同的 function。
您可以使用itertools.combinations
獲取所有可能的索引組合,並像您一樣設置1
:
from itertools import combinations
def ff(n):
x_list = []
for combination in combinations(range(6), n):
new_list = [0 for x in range(6)]
for i in combination:
new_list[i] = 1
x_list.append(new_list)
return x_list
ff(1)
ff(2)
ff(3)
請注意,在文檔中,他們給出了combinations
本身如何實現的“示例代碼”,我認為這對您閱讀和理解會很有趣!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.