为了账号安全,请及时绑定邮箱和手机立即绑定

如何从列表中获取名称的所有组合

如何从列表中获取名称的所有组合

千万里不及你 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 关注
  • 216 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号