itertools产品生成所有可能的大小为3的字符串 [英] itertools product to generate all possible strings of size 3

查看:90
本文介绍了itertools产品生成所有可能的大小为3的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输入:

pos_1= 'AVNMHDRW' 
pos_2= 'KNTHDYBW'
pos_3= 'KVNGSDRB'

尝试使用pos_1中的一项,pos_2中的一项以及pos_3中的一项来查找所有可能的三元组

Trying to find all possible triplets using one item from pos_1, one from pos_2, and one from pos_3

我试图弄清楚如何使用itertools.product(*),但我有些困惑

I'm trying to figure out how to use itertools.product(*) but I'm a little confused

最终,我想通过从pos_1中获取一个,然后从pos_2中获取一个,再从pos_3中获取一个,来创建所有不同可能性的列表(或生成器对象)

Ultimately, I want to create a list (or generator object) of all the different possibilities by taking one from pos_1 then one from pos_2 and then one from pos_3

示例输出:

'AKK','ANV','WWB'

pos_1代表位置1,以此类推代表pos_2和pos_3.

pos_1 stands for position one and so on for pos_2 and pos_3.

推荐答案

简单:

itertools.product(pos_1, pos_2, pos_3)

这可以反复进行;如果需要列表,只需将其传递给list.

This can be iterated over; if you want a list, just pass it to list.

到底是什么问题?

这将生成每个源中项目的元组.如果您想将它们重新连接成字符串,则可以在进行迭代时手动执行以下操作:

This produces tuples of the items from each source. If you want to join them back into strings, you can do that manually when you iterate:

for a, b, c in itertools.product(pos_1, pos_2, pos_3):
    do_something_with(a + b + c)

或创建列表,您可以使用列表理解:

or to create the list, you can use a list comprehension:

[a + b + c for a, b, c in itertools.product(pos_1, pos_2, pos_3)]

这篇关于itertools产品生成所有可能的大小为3的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆