在python里,*号代表拆分,把list/tuple里的元素拆出来,如:
tu = (1, 2, 3)
print(tu) # (1, 2, 3) tuple
print(*tu) # 1 2 3 各个元素
li = [(1,2,3), (4,5,6), (7,8,9)]
print(li) #[ (1,2,3), (4,5,6), (7,8,9) ] 包含tuple的list
print(*li) # (1,2,3) (4,5,6) (7,8,9) 各个tuple
zip()的作用是交叉合并元素,就像拉链一样:
和numpy.transpose(1,0) 效果是一样的。zip再zip,就还原:list(zip(*li))
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
list(zip(*zip(*li)))
[(1,2,3), (4,5,6), (7,8,9)]
namedtuple是python collection里的一个类,有些类似于struct,一种简单的可以给元素命名的结构体,用法如下:
Friend = namedtuple("Friend",['name','age','email']) F1 = Friend('giga', 38, 'gaga@qq.com') print(F1) print(F1.name, F1[0]) print(F1.age, F1[1]) print(F1.email, F1[2])
Friend(name='giga', age=38, email='gaga@qq.com')
giga giga
38 38
gaga@qq.com gaga@qq.com
同样,对待namedtuple Transitions,也可以这样:
Transition = namedtuple('Transition',('state', 'action', 'next_state', 'reward')) T1 = Transition('A1', 'B1', 'C1', 'D1') T2 = Transition('A2', 'B2', 'C2', 'D2') T3 = Transition('A3', 'B3', 'C3', 'D3') transitions = (T1, T2, T3) batch = Transition(*zip(*transitions)) batch
Transition(state=('A1', 'A2', 'A3'), action=('B1', 'B2', 'B3'), next_state=('C1', 'C2', 'C3'), reward=('D1', 'D2', 'D3'))
网友评论