加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

在Python中编写这个“双管列表”的更好方法

发布时间:2020-12-20 11:39:29 所属栏目:Python 来源:网络整理
导读:我的意思是第12行的for循环和嵌套在其中的for循环.我不止一次遇到这种情况.我会使用列表理解,但似乎它不会在这里工作. import randomimport stringdef password_generator(): key = zip(string.digits,string.ascii_uppercase) cruft,x = str(random.random(
我的意思是第12行的for循环和嵌套在其中的for循环.我不止一次遇到这种情况.我会使用列表理解,但似乎它不会在这里工作.

import random

import string

def password_generator():
    key = zip(string.digits,string.ascii_uppercase)

    cruft,x = str(random.random()).split('.')

    pw = ''

    for item in x:
        for element in key:
            if item in element:
                Q = random.random()
                if Q > 0.7:
                    pw += element[1].lower()
                else:
                    pw += element[1]

    print pw

谢谢.

解决方法

这是一种使用列表理解的方法:

def pw_gen():
    key = zip(string.digits,x = str(random.random()).split('.')

    def f(i,e):
      Q = random.random()
      if Q > 0.7:
        return e[1].lower()
      else:
        return e[1]

    return [ f(item,element) for item in x for element in key if item in element ]

这将返回一个字符列表.使用“”.join(pw_gen())转换为字符串.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读