在没有ZIP的python中成对追加 [英] Pairwise appending in python without ZIP

查看:77
本文介绍了在没有ZIP的python中成对追加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用Python学习列表理解.我将如何执行以下操作:

I am currently learning list comprehension in Python. How would I do the following:

l1 = [2,4,6,8]
l2 = [2,3,4,5]
l = [*some list comprehension*]

这样

l = [[2,2],[4,3],[6,4],[8,5]]

我可以在没有zip的情况下执行此操作吗?

Can I do this without zip?

推荐答案

您需要 zip 函数.

You want the zip function.

示例-

>>> l1 = [2,4,6,8]
>>> l2 = [2,3,4,5]
>>>
>>> l = list(zip(l1,l2))
>>> l
[(2, 2), (4, 3), (6, 4), (8, 5)]

如果您希望内部列表的类型为list而不是元组-

If you want the inner lists to be of type list instead of tuple -

>>> l = [list(x) for x in zip(l1,l2)]
>>> l
[[2, 2], [4, 3], [6, 4], [8, 5]]

在python 3.x中,zip返回一个迭代器,因此,如果您不需要列表,而只想遍历每个组合(压缩)的元素,则可以直接使用-zip(l1,l2).

In python 3.x, zip returns an iterator, so if you do not want a list, but just want to iterate over each combined (zipped) element, you can just directly use - zip(l1,l2) .

按照问题的要求,要在没有zip函数的情况下执行此操作,可以使用 enumerate 函数从一个列表中获取索引以及元素,然后使用索引从第二个列表中获取元素.

As it is asked in the question, to do it without zip function, you can use enumerate function to get the index as well as the element from one list and then use the index to get the element from second list.

>>> l = [[x,l2[i]] for i,x in enumerate(l1)]
>>> l
[[2, 2], [4, 3], [6, 4], [8, 5]]

但是,除非两个列表的大小都相同,否则这是行不通的.也不确定为什么要不使用zip来做到这一点.

But this would not work unless both lists have same size.Also not sure why you would want to do it without zip .

这篇关于在没有ZIP的python中成对追加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆