Python推导式创建数列的方法

Python推导式创建数列的方法

一、列表推导式

列表推导式生成列表对象,语法如下:

"""
[表达式 for item in 可迭代对象]
或者
[表达式 for item in 可迭代对象 if 条件判断]
"""

例子

l1 = [x for x in range(5)]
print(l1)       # [0, 1, 2, 3, 4]

l2 = [x*2 for x in range(1,5)]
print(l2)       # [2, 4, 6, 8]

l3 = [x*2 for x in range(1,100) if x % 5 == 0]
print(l3)       # [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190]

l4 = [x for x in "abcdefghij"]
print(l4)       # ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]

l5 = [(row,col) for row in range(3) for col in range(1,4)]
print(l5)  # [(0, 1), (0, 2), (0, 3), (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3)]
for l6 in l5:
    print(l6)

二、字典推导式

字典推导式生成字典对象,语法如下:

"""
{key:value for 表达式 in 可迭代对象}
字典推导式也可以加if和多个for循环
"""

例子

# 统计字符串中各个字符出现的次数
#Python学习交流群:711312441
text = "i love liangxiaoxin,i can fall in love liangxiaoxin all the time."
count_dict = {d : text.count(d) for d in text}
print(count_dict)   # {"i": 10, " ": 10, "l": 8, "o": 4, "v": 2, "e": 4, "a": 7, "n": 6, "g": 2, "x": 4, ",": 1, "c": 1, "f": 1, "t": 2, "h": 1, "m": 1, ".": 1}

三、集合推导式

集合推导式生成集合,和列表推导式的语法格式类似,语法如下:

"""
{表达式 for item in 可迭代对象}
或者
{表达式 for item in 可迭代对象 if 条件判断}
"""

例子

s = {x for x in range(100) if x % 7 == 0}
print(s)    # {0, 98, 35, 70, 7, 42, 77, 14, 49, 84, 21, 56, 91, 28, 63}

四、生成器推导式

元组是没有推导式的,元组推导式生成的是一个生成器对象
一个迭代器只能运行一次,第一次迭代可以得到数据,第二次迭代不会显示数据

例子

t1 = (x*2 for x in range(1,100) if x % 9 == 0)
print(t1)     # <generator object <genexpr> at 0x00000257B30D69E8>
print(list(t1))    # [18, 36, 54, 72, 90, 108, 126, 144, 162, 180, 198]
print(tuple(t1))   # ()

t2 = (x*2 for x in range(1,100) if x % 9 == 0)
for t in t2:
    print(t,end="	")    # 18    36    54    72    90    108    126    144    162    180    198
hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » Python推导式创建数列的方法