zip(list) 和 zip(*list) 的区别 [英] Difference between zip(list) and zip(*list)

查看:73
本文介绍了zip(list) 和 zip(*list) 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个列表 p = [[1,2,3],[4,5,6]]

如果我这样做:

>>>d=zip(p)
>>>list(d)
[([1, 2, 3],), ([4, 5, 6],)]

不过,我真正想要的是使用这个:

Though, what I actually want is obtained using this:

>>>d=zip(*p)
>>>list(d)
[(1, 4), (2, 5), (3, 6)]

我发现在列表名称前添加*"会给出我需要的输出,但我无法弄清楚它们的操作有何不同.你能解释一下区别吗?

I have found out that adding a '*' before the list name gives my required output, but I can't make out the difference in their operation. Can you please explain the difference?

推荐答案

zip 想要将一堆参数压缩在一起,但您拥有的是一个参数(一个列表,其元素也列表).函数调用中的 * 会解包"一个列表(或其他可迭代对象),使其每个元素成为一个单独的参数.因此,如果没有 *,您正在执行 zip( [[1,2,3],[4,5,6]] ).使用 *,您正在执行 zip([1,2,3], [4,5,6]).

zip wants a bunch of arguments to zip together, but what you have is a single argument (a list, whose elements are also lists). The * in a function call "unpacks" a list (or other iterable), making each of its elements a separate argument. So without the *, you're doing zip( [[1,2,3],[4,5,6]] ). With the *, you're doing zip([1,2,3], [4,5,6]).

这篇关于zip(list) 和 zip(*list) 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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