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

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

如何從列表中獲取名稱的所有組合

如何從列表中獲取名稱的所有組合

千萬里不及你 2021-12-17 14:45:48
嘗試打印用戶生成的名稱列表的排列/組合時出現錯誤。我從 itertools 嘗試了一些東西,但無法讓排列或組合起作用。在連接字符串的過程中遇到了其他一些錯誤,但目前得到一個:TypeError: 'list' object not callable。我知道我犯了一個簡單的錯誤,但無法解決。請幫忙!from itertools import combinations name_list = []for i in range(0,20):    name = input('Add up to 20 names.\nWhen finished, enter "Done" to see all first and middle name combinations.\nName: ')    name_list.append(name)    if name != 'Done':        print(name_list)    else:        name_list.remove('Done')        print(name_list(combinations))我期望:1) 用戶向列表中添加一個名稱 2) 列表打印顯示列表中的用戶內容 3) 完成后,用戶輸入“完成”:a) 從列表中刪除“完成” b) 的所有組合打印清單上的剩余項目
查看完整描述

2 回答

?
至尊寶的傳說

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

排列和組合是兩種不同的野獸。看:


>>> from itertools import permutations,combinations

>>> from pprint import pprint

>>> l = ['a', 'b', 'c', 'd']

>>> pprint(list(combinations(l, 2)))

[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]

>>> pprint(list(permutations(l)))

[('a', 'b', 'c', 'd'),

 ('a', 'b', 'd', 'c'),

 ('a', 'c', 'b', 'd'),

 ('a', 'c', 'd', 'b'),

 ('a', 'd', 'b', 'c'),

 ('a', 'd', 'c', 'b'),

 ('b', 'a', 'c', 'd'),

 ('b', 'a', 'd', 'c'),

 ('b', 'c', 'a', 'd'),

 ('b', 'c', 'd', 'a'),

 ('b', 'd', 'a', 'c'),

 ('b', 'd', 'c', 'a'),

 ('c', 'a', 'b', 'd'),

 ('c', 'a', 'd', 'b'),

 ('c', 'b', 'a', 'd'),

 ('c', 'b', 'd', 'a'),

 ('c', 'd', 'a', 'b'),

 ('c', 'd', 'b', 'a'),

 ('d', 'a', 'b', 'c'),

 ('d', 'a', 'c', 'b'),

 ('d', 'b', 'a', 'c'),

 ('d', 'b', 'c', 'a'),

 ('d', 'c', 'a', 'b'),

 ('d', 'c', 'b', 'a')]

>>> 


查看完整回答
反對 回復 2021-12-17
?
白板的微信

TA貢獻1883條經驗 獲得超3個贊

對于使用組合,您需要將 r 作為參數。此代碼給出所有數字的所有組合(0 到列表長度),


from itertools import combinations 


name_list = []


for i in range(0,20):

    name = raw_input('Add up to 20 names.\nWhen finished, enter "Done" to see all first and middle name combinations.\nName: ')

    name_list.append(name)

    if name != 'Done':

        print(name_list)

    else:

        name_list.remove('Done')

        break


for i in range(len(name_list) + 1):

    print(list(combinations(name_list, i)))

    print("\n")


查看完整回答
反對 回復 2021-12-17
  • 2 回答
  • 0 關注
  • 201 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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