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

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

如何以數組形式訪問組合的元素?

如何以數組形式訪問組合的元素?

繁華開滿天機 2023-08-22 17:44:34
我試圖以數組的形式訪問組合列表的元素,以便能夠操縱組合的結果。a = 1b = 2c = 3d = 4comb = combinations_with_replacement([a, b, c, d], 2)for i in list(comb):     print(i) 我有這段代碼,a, b, c, d變量不會是那些特定值。這將返回:(1, 1)(1, 2)(1, 3)(1, 4)(2, 2)(2, 3)(2, 4)(3, 3)(3, 4)(4, 4)我希望能夠以數組的形式訪問每個組合來操作其元素,我該怎么做?
查看完整描述

2 回答

?
慕田峪9158850

TA貢獻1794條經驗 獲得超8個贊

寫一個包裝器。


def wrapper_combinations_with_replacement(iterable, r):

    comb = combinations_with_replacement(iterable, r)

    for item in comb:

        yield list(item)

現在你有了一個列表的列表。


a = 1

b = 2

c = 3

d = 4

comb = wrapper_combinations_with_replacement([a, b, c, d], 2)

for i in list(comb): 

    print(i)

結果是:


[1, 1]

[1, 2]

[1, 3]

[1, 4]

[2, 2]

[2, 3]

[2, 4]

[3, 3]

[3, 4]

[4, 4]

或者使用list


list(wrapper_combinations_with_replacement([a, b, c, d], 2))

結果:


[[1, 1],

 [1, 2],

 [1, 3],

 [1, 4],

 [2, 2],

 [2, 3],

 [2, 4],

 [3, 3],

 [3, 4],

 [4, 4]]


查看完整回答
反對 回復 2023-08-22
?
動漫人物

TA貢獻1815條經驗 獲得超10個贊

comb_list = [list(combination) for combination in (list(comb))]

這將為您提供一個數組形式的組合列表


for array_combination in comb_list:

    print(array_combination)


Output:


> [1, 1]

  [1, 2]

  [1, 3]

  [1, 4]

  [2, 2]

  [2, 3]

  [2, 4]

  [3, 3]

  [3, 4]

  [4, 4]


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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