Python语法学习八之强化学习

一、列表推导式

所谓的列表推导式,就是指的轻量级循环创建列表

1-1、简单方式
a = [x for x in range(4)]
print a
# [0, 1, 2, 3]
1-2、循环的过程中使用if
a = [x for x in range(3, 10) if x % 2 == 0]
print a
# [4, 6, 8]
1-3、2个for循环
a = [(x, y) for x in range(1, 3) for y in range(3)]
print a
# [(1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
1-4、3个for循环
a = [(x, y, z) for x in range(1, 3) for y in range(3) for z in range(4, 6)]
print a

# [(1, 0, 4), (1, 0, 5), (1, 1, 4), (1, 1, 5), (1, 2, 4), (1, 2, 5), (2, 0, 4), (2, 0, 5), (2, 1, 4), (2, 1, 5), (2, 2, 4), (2, 2, 5)]

二、set、list、tuple相互转换

2-1、多维元组全部转换成列表
a = ((1,2,3),(4,5,6,),(7,8,9))
b = list(a)
print(b)
for c in b:b[b.index(c)] = list(c)
print(b)
# [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
2-2、list()、tuple()、join()
  1. list()方法是把str或元组转换成列表
>>>a="abcde"
>>>list(a)
['a','b','c','d','e']
  1. tuple()方法是把str或列表转换成元组
>>>tuple(a)
('a','b','c','d','e')
>>>tuple(list(a))
  1. join函数是把列表和元组转换成str
>>> " ".join(tuple(a))
'abcde'
>>> " ".join(list(a))
‘abcde’

你可能感兴趣的:(Python语法学习八之强化学习)