我知道如何使用组合生成3位数组合,并且可以显示结果,但是我一生无法弄清楚如何从此步骤将生成的3位数组合列表保存到我可以保存到txt文件的实际列表。任何帮助将不胜感激。
我正在尝试生成3位数字的组合列表,然后可以测试编写的脚本以获取列表的txt文件并针对3位数字的密码保护文件对其进行测试。我真的只需要帮助弄清楚如何从组合中获取结果以保存到列表中。
comb = combinations([1, 2, 3,4,5,6,7,8,9], 3)
for i in list(comb):
print i
如果可以确定结果,则将运行组合,并将结果保存到可以写入文件的列表中。
答案 0 :(得分:1)
您可以直接将其转换为列表...
from itertools import combinations
comb_list = list(combinations([1, 2, 3,4,5,6,7,8,9], 3))
> [(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 2, 6), (1, 2, 7), (1, 2, 8), (1, 2, 9), (1, 3, 4), (1, 3, 5), (1, 3, 6), (1, 3, 7), (1, 3, 8), (1, 3, 9), (1, 4, 5), (1, 4, 6), (1, 4, 7), (1, 4, 8), (1, 4, 9), (1, 5, 6), (1, 5, 7), (1, 5, 8), (1, 5, 9), (1, 6, 7), (1, 6, 8), (1, 6, 9), (1, 7, 8), (1, 7, 9), (1, 8, 9), (2, 3, 4), (2, 3, 5), (2, 3, 6), (2, 3, 7), (2, 3, 8), (2, 3, 9), (2, 4, 5), (2, 4, 6), (2, 4, 7), (2, 4, 8), (2, 4, 9), (2, 5, 6), (2, 5, 7), (2, 5, 8), (2, 5, 9), (2, 6, 7), (2, 6, 8), (2, 6, 9), (2, 7, 8), (2, 7, 9), (2, 8, 9), (3, 4, 5), (3, 4, 6), (3, 4, 7), (3, 4, 8), (3, 4, 9), (3, 5, 6), (3, 5, 7), (3, 5, 8), (3, 5, 9), (3, 6, 7), (3, 6, 8), (3, 6, 9), (3, 7, 8), (3, 7, 9), (3, 8, 9), (4, 5, 6), (4, 5, 7), (4, 5, 8), (4, 5, 9), (4, 6, 7), (4, 6, 8), (4, 6, 9), (4, 7, 8), (4, 7, 9), (4, 8, 9), (5, 6, 7), (5, 6, 8), (5, 6, 9), (5, 7, 8), (5, 7, 9), (5, 8, 9), (6, 7, 8), (6, 7, 9), (6, 8, 9), (7, 8, 9)]
编辑
获得3位数字的字符串
[str(a[0])+str(a[1])+str(a[2]) for a in combinations([1,2,3,4,5,6,7,8,9], 3)]
> ['123', '124', '125', '126', '127', '128', '129', '134', '135', '136', '137', '138', '139', '145', '146', '147', '148', '149', '156', '157', '158', '159', '167', '168', '169', '178', '179', '189', '234', '235', '236', '237', '238', '239', '245', '246', '247', '248', '249', '256', '257', '258', '259', '267', '268', '269', '278', '279', '289', '345', '346', '347', '348', '349', '356', '357', '358', '359', '367', '368', '369', '378', '379', '389', '456', '457', '458', '459', '467', '468', '469', '478', '479', '489', '567', '568', '569', '578', '579', '589', '678', '679', '689', '789']
这等效于
ans = []
for comb in combinations([1,2,3,4,5,6,7,8,9], 3):
ans.append(str(comb[0])+str(comb[1])+str(comb[2]))
或者更好地使用连接
''.join(str(num) for num in (1, 2, 3))
> '123'
给予
[''.join(str(num) for num in a) for a in combinations([1,2,3,4,5,6,7,8,9], 3)]