字母组合如何用python实现_python

#!/usr/bin/python

import random

lower_a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

upper_a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

num = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

all = []

all = " ".join("".join(lower_a) + "".join(upper_a) + "".join(num))

all = all.split()

x = 1

c = 1

while x < 10:

y = []

for i in range(c):

a = random.choice(all)

y.append(a)

print "".join(y)

x += 1

c += 1

我现在有什么输出如下:

5

hE

HAy

1kgy

Pt6JM

2pFuCb

Jv5osaX

5q8PwWAO

SvHWRKfI5

如何让它系统地遍历给定长度的每个字母组合(大写和小写),然后在该长度上加1并重复该过程?

解决方法:

最好不要重新创建标准库中已有的功能.

看一下标准库模块“itertools”.

特别是combination(),permutations()和product()函数.

import itertools

lower_a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

upper_a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

num = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

all = []

all = lower_a + upper_a + num

for r in range(1, 3):

for s in itertools.product(all, repeat=r):

print ''.join(s)

如果您的Python版本较旧,则可能无法访问这些功能.但是,如果您查看Python 2.6的文档,您可以看到如何在Python中实现所有这些函数.例如,itertools.product的实现如下:

def product(*args, **kwds):

# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy

# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111

pools = map(tuple, args) * kwds.get('repeat', 1)

result = [[]]

for pool in pools:

result = [x+[y] for x in result for y in pool]

for prod in result:

yield tuple(prod)

您也可以尝试使用递归解决方案:

lower_a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

upper_a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

num = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

all = []

all = lower_a + upper_a + num

def recursive_product(myList, length, myString = ""):

if length == 0:

print myString

return

for c in myList:

recursive_product(myList, length-1, myString + c)

for r in range(1, 3):

recursive_product(all, r)

标签:choice,python,arrays,string,random

来源: https://codeday.me/bug/20191007/1865727.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值