推导式温习_1

推导式温习

print('-'*10,'Introducing Python_CN_Bill Lubanovic_Python语言及其应用','-'*10)
print('-'*10,'4.6.1列表推导式','-'*10)
number_list_1 = []
number_list_1.append(1)
number_list_1.append(2)
number_list_1.append(3)
number_list_1.append(4)
number_list_1.append(5)
print(number_list_1)

print('-'*20)

number_list_2 = []
for number in range(1,10):
    number_list_2.append(number)
print(number_list_2)

print('-'*20)

number_list_3 = list(range(1,20))
print(number_list_3)

print('-'*20,'像下面这样的语法更像推导式','-'*20)
print('number_list_comprehension_1 = [number for number in range(1,20)]')
#第1个number为列表变量生成值,第2个number为循环变量
number_list_comprehension_1 = [number for number in range(1,20)]
print(number_list_comprehension_1)

#
number_list_comprehension_2 = [number-1 for number in range(1,20)]
print(number_list_comprehension_2)

a_list_1 = [number for number in range(1,6) if number % 2 ==1]
print(a_list_1)

a_list_2 = [number for number in range(1,6) if number % 2 ==0]
print(a_list_2)

#传统生成奇数的方法:
odd_1 = []
for number in range(1,6):
    if number % 2 == 1:
        odd_1.append(number)
print('传统生成奇数的方法:',odd_1)

#嵌套循环例子:
rows = range(1,4)
cols = range(1,3)
for row in rows:
    for col in cols:
        print(row,col)

#使用一次推导,将结果复制给变量cells,使它成为元组(row,col):
cells = [(row,col) for row in range(1,4) for col in range(1,3)]
print('输出元组:')
for cell in cells:
    print(cell)
print('拆封元组将变量取出:')    
for row,col in cells:
    print(row,col)


print('-'*10,'4.6.2 字典推导式','-'*10)
word_1 = 'letters'
letter_counts = {letter:word_1.count(letter) for letter in word_1}
print(letter_counts)
print('在字典中迭代的时间长,因有重复的字符个数',{letter:word_1.count(letter) for letter in word_1})
print('在集合中迭代的时间短',{letter:word_1.count(letter) for letter in set(word_1)})


print('-'*10,'4.6.3 集合推导式','-'*10)
a_set = {number for number in range(1,6) if number % 3 ==1}
print('集合推导式 range(1,6) 范围内 number % 3 = ',a_set)

print('-'*10,'4.6.4 生成器推导式','-'*10)
number_thing = (number for number in range(1,6))
print(type(number_thing))

print('对生成器进行迭代 for number in number_thing:')
for number in number_thing:
    print(number)

number_thing_a = (number for number in range(1,6))
number_list_a = list(number_thing_a)
print(number_list_a)

print('再一次迭代生成器,发现它已经被废除了:')
try_again = list(number_thing_a)
print(try_again)

 

posted @ 2022-05-14 22:51  CDPJ  阅读(16)  评论(0编辑  收藏  举报