如何在 Python 中压缩未知数量的列表?

发布于 2024-11-06 03:32:13 字数 346 浏览 0 评论 0原文

假设我有以下列表:

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 技术交流群。

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

发布评论

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

评论(2

哆兒滾 2024-11-13 03:32:14

添加到上面的答案中,解包允许您将函数参数作为数组而不是多个参数传递到函数中。文档中给出了以下示例:

list(range(3, 6))            # normal call with separate arguments
[3, 4, 5]
args = [3, 6]
list(range(*args))            # call with arguments unpacked from a list
[3, 4, 5]

对于 zip() 来说,这对我来说非常方便,因为我正在整理一些逻辑,我希望能够灵活地适应我的维度数数据。这意味着首先将这些维度收集到一个数组中,然后使用解包运算符将它们提供给 zip() 。

myData = []
myData.append(range(1,5))
myData.append(range(3,7))
myData.append(range(10,14))

zippedTuple = zip(*myData)

print(list(zippedTuple))

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:

list(range(3, 6))            # normal call with separate arguments
[3, 4, 5]
args = [3, 6]
list(range(*args))            # call with arguments unpacked from a list
[3, 4, 5]

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 to zip() with the unpack operator.

myData = []
myData.append(range(1,5))
myData.append(range(3,7))
myData.append(range(10,14))

zippedTuple = zip(*myData)

print(list(zippedTuple))
伴我老 2024-11-13 03:32:13

您可以使用 * 将列表解压到位置参数:

zip(assignment, *grades)

You can use * to unpack a list into positional parameters:

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