亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

比如指定長度2,就會得到[1,2][2,3][1,3],不考慮順序

比如指定長度2,就會得到[1,2][2,3][1,3],不考慮順序

MMMHUHU 2023-04-25 16:12:17
python怎么生成list的所有元素的組合比如l = [1,2,3]指定長度2,就會得到[1,2][2,3][1,3],不考慮順序。
查看完整描述

2 回答

?
絕地無雙

TA貢獻1946條經驗 獲得超4個贊

生成排列可以用product:

from itertools import productl = [1, 2, 3]print list(product(l, l))print list(product(l, repeat=4))

組合的話可以用combinations:

from itertools import combinationsprint list(combinations([1,2,3,4,5], 3))

下面是我以為沒有combinations然后自己寫的,沒有itertools的python(2.6以下)可供參考。

import copydef combine(l, n): 
    answers = []
    one = [0] * n 
    def next_c(li = 0, ni = 0): 
        if ni == n:
            answers.append(copy.copy(one))            return
        for lj in xrange(li, len(l)):
            one[ni] = l[lj]
            next_c(lj + 1, ni + 1)
    next_c()    return answersprint combine([1, 2, 3, 4, 5], 3)

輸出:

[[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2, 3, 5], [2, 4, 5], [3, 4, 5]]


查看完整回答
反對 回復 2023-04-28
?
慕斯王

TA貢獻1864條經驗 獲得超2個贊

import itertools
nums = itertools.permutations([1,2,3])for x in  nums:    print(x)>>> (1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)


查看完整回答
反對 回復 2023-04-28
  • 2 回答
  • 0 關注
  • 121 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號