列表推导式和seed()的理解

Table of Contents generated with DocToc

列表推导式和seed()的理解

对seed()的理解

  某些场合为了得到两个一模一样的随机数系列,可以使用seed()来实现

即同一个种子可以得到的随机序列必定相同

import random

random.seed(0)
lst=[random.random() for i in range(5)]

random.seed(0)
lst1=[random.random() for i in range(5)]

print(lst==lst1)
#True
#lst必定等于lst1

列表推导式

  List Comprehensions is fast, readable and use less code

第一种用法

  out_list = [out_express for out_express in input_list if out_express_condition]


out_list = [out_express for out_express in input_list if out_express_condition]
#其中的 if 条件判断根据需要可有可无。
animal_doctor = [animal for animal in animal_park]

nimal_doctor = [animal for animal in animal_park if animal != 'Dog'and animal != 'Cat']

digit=[chr(i) for i in range(48,57)]
letters=[chr(i) for i in range(ord('A'),ord('z'))]+
[chr(i) for i in range(ord('a'),ord('z'))]

第二种用法

  列表推导式的项可以是任意的,包括列表

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
]

matrix2=[[row[i] for row in matrix] for i in range(4)]

'''
transposed = []
for i in range(4):
    transposed.append([row[i] for row in matrix])

#细看  [row[0] for row in matrix]

transposed = []
for i in range(4):
    # the following 3 lines implement the nested listcomp
    transposed_row = []
    for row in matrix:
        transposed_row.append(row[i])
    transposed.append(transposed_row)

transposed

'''
flattened = []

for row in matrix:
    for i in row:
        flattened.append(i)

flattened = [i for row in matrix for i in row]

python官方文档

posted @ 2020-03-19 18:32  qwfand  阅读(184)  评论(0编辑  收藏  举报