是否有Python内置函数可以从多个列表创建元组?
是否有一个 python 内置函数与 tupler 对于一组列表执行相同的操作,或者类似的东西:
def tupler(arg1, *args):
length = min([len(arg1)]+[len(x) for x in args])
out = []
for i in range(length):
out.append(tuple([x[i] for x in [arg1]+args]))
return out
所以,例如:
tupler([1,2,3,4],[5,6,7])
returns:
[(1,5),(2,6),(3,7)]
或者也许有正确的 pythony 方法来执行此操作,或者是否有类似的生成器???
Is there a python builtin that does the same as tupler for a set of lists, or something similar:
def tupler(arg1, *args):
length = min([len(arg1)]+[len(x) for x in args])
out = []
for i in range(length):
out.append(tuple([x[i] for x in [arg1]+args]))
return out
so, for example:
tupler([1,2,3,4],[5,6,7])
returns:
[(1,5),(2,6),(3,7)]
or perhaps there is proper pythony way of doing this, or is there a generator similar???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为您正在寻找
zip()
:I think you're looking for
zip()
:看看内置的 zip 函数 http://docs.python.org/library /functions.html#zip
它还可以处理两个以上的列表,比如 n,然后创建 n 元组。
have a look at the built-in zip function http://docs.python.org/library/functions.html#zip
it can also handle more than two lists, say n, and then creates n-tuples.
正确的方法是使用 zip 函数。
或者,我们可以使用列表推导式和内置的
enumerate
函数达到同样的结果。
上面示例的缺点是我们并不总是迭代具有最小长度的列表。
The proper way is to use the
zip
function.Alternativerly we can use list comprehensions and the built-in
enumerate
functionto achieve the same result.
The drawback in the above example is that we don't always iterate over the list with the minimum length.