itertools模块的zip

mac2024-04-16  44

【pytorch】关于Embedding和GRU、LSTM的使用详解

原文章:https://www.cnblogs.com/duye/p/10590146.html

 

文章中在变换句子矩阵的时候使用了itertools模块的zip_longest函数。使用方法如下:

batch = list(itertools.zip_longest(batch,fillvalue=PAD)) # fillvalue就是要填充的值,强制转成list

这个函数一般的使用方法为:

res = zip_longest('abc', '12') for x in res:   print(x) #('a', '1') #('b', '2') #('c', None)

但是batch是一个嵌套list,如果按照上面的用法,列为:

res = zip_longest(batch[0],batch[1],batch[2]...)

不合理,因为不知道batch的长度,而且这样遍历有点不方便。网上找不到合适的解决方案,于是我开始尝试,利用了指针的思想,真的试出来了!答案就是在batch前面加一个 * ,如下:

res = zip_longest(*batch)

 

欢迎留言

 

 

最新回复(0)