这是一个python zip的初学者问题。 我现在正在做 udacity 深度学习作业 LSTM。 有一行代码我不明白它是如何工作的。
s = [''.join(x) for x in zip(s, characters(b))]
它是从下面的上下文中复制的。
def batches2string(batches):
"""Convert a sequence of batches back into their (most likely) string
representation."""
s = [''] * batches[0].shape[0]
for b in batches:
s = [''.join(x) for x in zip(s, characters(b))]
return s
我尝试在 for 循环中重写它,但似乎我做得不正确。有人可以帮我如何在 for 循环中重写它吗?
s1 = [''] * batches[0].shape[0]
for b in batches:
for x in zip(s1, characters(b)):
print(x)
s1.append(x)
print(s1)
最佳答案
循环中的
x
与 tuple
匹配。
另一种语法是for a,b in zip
,但这里将元组传递给join
会更简单。在循环中相当于:
s1.append("".join(x))
如果你问我的话,这有点过分了,因为你只有 2 个值要加入
。另一种方法是:
for a,b in zip(s1, characters(b)):
s1.append(a+b)
为了理解:
s = [a+b for a,b in zip(s, characters(b))]
join
在这种情况下并没有更快,因为我们只需要添加 2 个术语,没有任何分隔符,并且 join
是一个函数调用。
编辑:现在我很好奇,我正在对此进行测试:
l = ["foo","bar","spam","egg""hello","world"]
start = time.time()
for _ in range(10000000):
s = [a+b for a,b in zip(l,l)]
end = time.time()
print("elapsed {}".format(end-start))
运行时间为14.80
秒。
现在替换为:
s = ["".join(x) for x in zip(l,l)]
它的运行时间为17.75
秒。因此,+
一次获胜... join
有助于避免对字符串求和的二次效应,即如果要求和的字符串超过 2 个...
不要在此处使用join
,当您有两个以上的值需要连接和/或中间有分隔符时,请使用它。
关于python - 这段代码中的 zip 是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46481885/