是否有Python内置函数可以从多个列表创建元组?

发布于 2024-10-31 17:01:49 字数 450 浏览 0 评论 0原文

是否有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

谈下烟灰 2024-11-07 17:01:49

我认为您正在寻找 zip()

>>> zip([1,2,3,4],[5,6,7])
[(1, 5), (2, 6), (3, 7)]

I think you're looking for zip():

>>> zip([1,2,3,4],[5,6,7])
[(1, 5), (2, 6), (3, 7)]
云柯 2024-11-07 17:01:49

看看内置的 zip 函数 http://docs.python.org/library /functions.html#zip

它还可以处理两个以上的列表,比如 n,然后创建 n 元组。

>>> zip([1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14])
 [(1, 5, 9, 13), (2, 6, 10, 14)]

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([1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14])
 [(1, 5, 9, 13), (2, 6, 10, 14)]
|煩躁 2024-11-07 17:01:49
zip([1,2,3,4],[5,6,7])

--->[(1,5),(2,6),(3,7)]


args = [(1,5),(2,6),(3,7)]

zip(*args)

--->[1,2,3],[5,6,7]
zip([1,2,3,4],[5,6,7])

--->[(1,5),(2,6),(3,7)]


args = [(1,5),(2,6),(3,7)]

zip(*args)

--->[1,2,3],[5,6,7]
残月升风 2024-11-07 17:01:49

正确的方法是使用 zip 函数。

或者,我们可以使用列表推导式和内置的 enumerate 函数
达到同样的结果。

>>> L1 = [1,2,3,4]
>>> L2 = [5,6,7]
>>> [(value, L2[i]) for i, value in enumerate(L1) if i < len(L2)]
[(1, 5), (2, 6), (3, 7)]
>>> 

上面示例的缺点是我们并不总是迭代具有最小长度的列表。

The proper way is to use the zip function.

Alternativerly we can use list comprehensions and the built-in enumerate function
to achieve the same result.

>>> L1 = [1,2,3,4]
>>> L2 = [5,6,7]
>>> [(value, L2[i]) for i, value in enumerate(L1) if i < len(L2)]
[(1, 5), (2, 6), (3, 7)]
>>> 

The drawback in the above example is that we don't always iterate over the list with the minimum length.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文