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——列表生成式