在 Python 中迭代列表
我试图迭代一个列表并获取列表的每个部分,对其进行编码并在全部完成后将结果连接起来。例如,我有一个字符串,它生成一个列表,每个元素的长度为 16 个字符。
message = (u'sixteen-letters.sixteen-letters.sixteen-letters.sixteen-letters.')
result = split16(message, 16)
msg = ';'.join(encode(result.pop(0)) for i in result)
编码函数采用 16 字节字符串并返回结果。然而,按照它的编写方式,它只编码列表中一半的元素。
如果我尝试理解:
result = [encode(split16(message, 16) for message in list_of_messages)]
result = ''.join(result)
它会导致整个列表立即发送。我需要做的是将每个元素分别发送到编码函数,获取结果然后将它们连接在一起。
有没有一种简单的方法可以实现这一目标?
I am trying to iterate through a list and take each part of the list, encode it and join the result up when it is all done. As an example, I have a string which produces a list with each element being 16 characters in length.
message = (u'sixteen-letters.sixteen-letters.sixteen-letters.sixteen-letters.')
result = split16(message, 16)
msg = ';'.join(encode(result.pop(0)) for i in result)
The encode function takes a 16 byte string and returns the result. However with the way it is written, it only encodes half of the elements in the list.
If I try comprehension:
result = [encode(split16(message, 16) for message in list_of_messages)]
result = ''.join(result)
It results in the whole list being sent at once. What I need to do is send each element to the encode function separately, get the result then join them together.
Is there an easy way of achieving this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你想做这样的事情吗?
当然,
如果您的 split16 函数足够复杂,也可能是这样。
Are you trying to do something like this?
of course it could be just
if your
split16
function complicated enough.我对你到底想要做什么有点困惑,你发布的代码中缺少一个括号,这让情况更加复杂:
应该是:
或:
我认为第二个会做你想做的事。
这段代码
失败了,因为在每一步你都在迭代
result
,但在每一步都用pop
缩短它。它应该只是:I am a bit confused about what you are exactly trying to do, which is compounded by a missing paren in the code you posted:
Should that be:
or:
I think the second will do what you want.
This code:
is failing because at every step you are iterating through
result
, but shortening it at every step withpop
. It should just be:我不太清楚你在追求什么,但是
I'm not quite clear what you are after, but