如何在 Python 中压缩未知数量的列表?
假设我有以下列表:
assignment = ['Title', 'Project1', 'Project2', 'Project3']
grades = [ ['Jim', 45, 50, 55], \
['Joe', 55, 50, 45], \
['Pat', 55, 60, 65] ]
我可以使用以下代码来压缩列表:
zip(assignment, grades[0], grades[1], grades[2])
如果成绩列表包含未知数量的项目,我将如何使用 zip 函数来压缩此列表?
Let's say I have the following lists:
assignment = ['Title', 'Project1', 'Project2', 'Project3']
grades = [ ['Jim', 45, 50, 55], \
['Joe', 55, 50, 45], \
['Pat', 55, 60, 65] ]
I could zip the lists using the following code:
zip(assignment, grades[0], grades[1], grades[2])
How would I use the zip function to zip this if the grades list contains an unkown number of items?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
添加到上面的答案中,解包允许您将函数参数作为数组而不是多个参数传递到函数中。文档中给出了以下示例:
对于
zip()
来说,这对我来说非常方便,因为我正在整理一些逻辑,我希望能够灵活地适应我的维度数数据。这意味着首先将这些维度收集到一个数组中,然后使用解包运算符将它们提供给 zip() 。Adding to sth's answer above, unpacking allows you to pass in your function parameters as an array rather than multiple parameters into the function. The following example is given in documentation:
In the case of
zip()
this has been extremely handy for me as I'm putting together some logic that I want to be flexible to the number of dimensions in my data. This means first collecting each of these dimensions in an array and then providing them tozip()
with the unpack operator.您可以使用
*
将列表解压到位置参数:You can use
*
to unpack a list into positional parameters: