猿问

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

尝试打印用户生成的名称列表的排列/组合时出现错误。


我从 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) 的所有组合打印清单上的剩余项目


千万里不及你
浏览 217回答 2
2回答

至尊宝的传说

排列和组合是两种不同的野兽。看:>>> 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')]>>> 

白板的微信

对于使用组合,您需要将 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')        breakfor i in range(len(name_list) + 1):    print(list(combinations(name_list, i)))    print("\n")
随时随地看视频慕课网APP

相关分类

Python
我要回答