python列表生成式

python——列表生成式

列表生成式即List    Comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式。

          列表生成式的结构是在一个中括号里包含一个表达式,然后是一个for语句,然后是0个或多个for或者if语句。列表表达式可以是任意的,意思是你可以在列表中放入任意类型的对象。返回结果将是一个新的列表,在这个以if和for语句为上下文的表达式运行完成之后产生。

格式:

variable    =    [out_exp    for    out_exp    in    input_list    if    out_exp    ==    2]
import random
a="".join(["('%s', '', 'test123', '2019-12-17'), \n"%str(i+100000) for i in range(10)])
print(a)

b="".join([random.choice('0123456789') for i in range(8)])
print(b)

执行结果:

/Library/Frameworks/Python.framework/Versions/3.7/bin/python3 /Users/shimo/PycharmProjects/lovetest/testDemo/test_01.py
('100000', '', 'test123', '2019-12-17'), 
('100001', '', 'test123', '2019-12-17'), 
('100002', '', 'test123', '2019-12-17'), 
('100003', '', 'test123', '2019-12-17'), 
('100004', '', 'test123', '2019-12-17'), 
('100005', '', 'test123', '2019-12-17'), 
('100006', '', 'test123', '2019-12-17'), 
('100007', '', 'test123', '2019-12-17'), 
('100008', '', 'test123', '2019-12-17'), 
('100009', '', 'test123', '2019-12-17'), 

11069321

Process finished with exit code 0

 

以下是用python语言随机生成10个随机手机号码!
import random


def createPhone():
    for k in range(10):
        prelist=["130", "131", "132", "133", "134", "135", "136", "137", "138", "139",
                 "147", "150", "151", "152", "153", "155", "156", "157", "158", "159",
                 "186", "187", "188", "189"]
        print random.choice(prelist)+"".join(random.choice("0123456789") for i in range(8))

createPhone()

参考文章:python——列表生成式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值