Python 中的 Zip 列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13704860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 09:25:03  来源:igfitidea点击:

Zip lists in Python

pythonpython-2.7

提问by AJW

I am trying to learn how to "zip" lists. To this end, I have a program, where at a particular point, I do the following:

我正在尝试学习如何“压缩”列表。为此,我有一个程序,在特定点上,我执行以下操作:

x1, x2, x3 = stuff.calculations(withdataa)

This gives me three lists, x1, x2, and x3, each of, say, size 20.

这给了我三个列表,x1x2x3,每个列表的大小为 20。

Now, I do:

现在,我这样做:

zipall = zip(x1, x2, x3)

However, when I do:

但是,当我这样做时:

print "len of zipall %s" % len(zipall)

I get 20, which is not what I expected. I expected three. I think I am doing something fundamentally wrong.

我得到了 20,这不是我的预期。我期待三个。我认为我在做一些根本错误的事情。

采纳答案by NPE

When you zip()together three lists containing 20 elements each, the result has twenty elements. Each element is a three-tuple.

当您zip()将三个包含 20 个元素的列表放在一起时,结果有 20 个元素。每个元素都是一个三元组。

See for yourself:

你自己看:

In [1]: a = b = c = range(20)

In [2]: zip(a, b, c)
Out[2]: 
[(0, 0, 0),
 (1, 1, 1),
 ...
 (17, 17, 17),
 (18, 18, 18),
 (19, 19, 19)]

To find out how many elements each tuple contains, you could examine the length of the first element:

要找出每个元组包含多少个元素,您可以检查第一个元素的长度:

In [3]: result = zip(a, b, c)

In [4]: len(result[0])
Out[4]: 3

Of course, this won't work if the lists were empty to start with.

当然,如果列表一开始是空的,这将不起作用。

回答by StoryTeller - Unslander Monica

zipcreates a new list, filled with tuples containing elements from the iterable arguments:

zip创建一个新列表,其中填充了包含来自可迭代参数的元素的元组:

>>> zip ([1,2],[3,4])
[(1,3), (2,4)]

I expect what you try to so is create a tuple where each element is a list.

我希望您尝试创建一个元组,其中每个元素都是一个列表。

回答by Katriel

ziptakes a bunch of lists likes

zip需要一堆列表喜欢

a: a1 a2 a3 a4 a5 a6 a7...
b: b1 b2 b3 b4 b5 b6 b7...
c: c1 c2 c3 c4 c5 c6 c7...

and "zips" them into one list whose entries are 3-tuples (ai, bi, ci). Imagine drawing a zipper horizontally from left to right.

并将它们“压缩”到一个条目为 3-tuples 的列表中(ai, bi, ci)。想象一下从左到右水平绘制拉链。

回答by Wagh

Basically the zip function works on lists, tuples and dictionaries in Python. If you are using IPython then just type zip? And check what zip() is about.

基本上 zip 函数适用于 Python 中的列表、元组和字典。如果您使用的是 IPython,那么只需输入 zip?并检查 zip() 是关于什么的。

If you are not using IPython then just install it: "pip install ipython"

如果您不使用 IPython,则只需安装它:“pip install ipython”

For lists

对于列表

a = ['a', 'b', 'c']
b = ['p', 'q', 'r']
zip(a, b)

The output is [('a', 'p'), ('b', 'q'), ('c', 'r')

输出是 [('a', 'p'), ('b', 'q'), ('c', 'r')

For dictionary:

对于字典:

c = {'gaurav':'waghs', 'nilesh':'kashid', 'ramesh':'sawant', 'anu':'raje'}
d = {'amit':'wagh', 'swapnil':'dalavi', 'anish':'mane', 'raghu':'rokda'}
zip(c, d)

The output is:

输出是:

[('gaurav', 'amit'),
 ('nilesh', 'swapnil'),
 ('ramesh', 'anish'),
 ('anu', 'raghu')]

回答by Ajay

In Python 2.7 this might have worked fine:

在 Python 2.7 中,这可能工作正常:

>>> a = b = c = range(20)
>>> zip(a, b, c)

But in Python 3.4 it should be (otherwise, the result will be something like <zip object at 0x00000256124E7DC8>):

但在 Python 3.4 中它应该是(否则,结果将类似于<zip object at 0x00000256124E7DC8>):

>>> a = b = c = range(20)
>>> list(zip(a, b, c))

回答by transang

For the completeness's sake.

为了完整起见。

When zipped lists' lengths are not equal. The result list's length will become the shortest one without any error occurred

当压缩列表的长度不相等时。结果列表的长度将成为最短的,不会发生任何错误

>>> a = [1]
>>> b = ["2", 3]
>>> zip(a,b)
[(1, '2')]

回答by JBallin

Source: My Blog Post (better formatting)

来源:我的博客文章(更好的格式)

Example

例子

numbers = [1,2,3]
letters = 'abcd'

zip(numbers, letters)
# [(1, 'a'), (2, 'b'), (3, 'c')]

Input

输入

Zero or more iterables [1] (ex. list, string, tuple, dictionary)

零个或多个可迭代对象 [1](例如列表、字符串、元组、字典)

Output(list)

输出(列表)

1st tuple = (element_1 of numbers, element_1 of letters)

2nd tuple = (e_2 numbers, e_2 letters)

n-th tuple = (e_n numbers, e_n letters)

第一个元组 =(数字的 element_1,字母的 element_1)

第二个元组 =(e_2 个数字,e_2 个字母)

第 n 个元组 =(e_n 个数字,e_n 个字母)

  1. List of n tuples: n is the length of the shortest argument (input)
    • len(numbers) == 3 < len(letters) == 4 → short= 3 → return 3 tuples
  2. Length each tuple = # of args (tuple takes an element from each arg)
    • args = (numbers,letters); len(args) == 2 → tuple with 2 elements
  3. ith tuple = (element_i arg1, element_i arg2…, element_i argn)
  1. n 个元组的列表:n 是最短参数(输入)的长度
    • len(numbers) == 3 < len(letters) == 4 → short= 3 → 返回 3 个元组
  2. 每个元组的长度 = # of args(元组从每个 arg 中获取一个元素)
    • args =(数字,字母);len(args) == 2 → 2 个元素的元组
  3. i第元组 = (element_i arg1, element_i arg2…, element_i arg n)

Edge Cases

边缘情况

1) Empty String: len(str)= 0 = no tuples

1) 空字符串:len(str)= 0 = 没有元组

2) Single String: len(str) == 2 tuples with len(args) == 1 element(s)

2) 单个字符串:len(str) == 2 个元组,其中 len(args) == 1 个元素

zip()
# []
zip('')
# []
zip('hi')
# [('h',), ('i',)]


Zip in Action!

拉链在行动!

1. Build a dictionary [2] out of two lists

1.用两个列表构建字典[2]

keys = ["drink","band","food"]
values = ["La Croix", "Daft Punk", "Sushi"]

my_favorite = dict( zip(keys, values) )

my_favorite["drink"]
# 'La Croix'

my_faves = dict()
for i in range(len(keys)):
    my_faves[keys[i]] = values[i]
  • zipis an elegant, clear, & concise solution
  • zip是一个优雅、清晰、简洁的解决方案

2. Print columns in a table

2. 打印表格中的列

"*" [3] is called "unpacking": f(*[arg1,arg2,arg3]) == f(arg1, arg2, arg3)

“*”[3] 被称为“解包”: f(*[arg1,arg2,arg3]) == f(arg1, arg2, arg3)

student_grades = [
[   'Morty'  ,  1   ,  "B"  ],
[   'Rick'   ,  4   ,  "A"  ],
[   'Jerry'  ,  3   ,  "M"  ],
[  'Kramer'  ,  0   ,  "F"  ],
]

row_1 = student_grades[0]
print row_1
# ['Morty', 1, 'B']

columns = zip(*student_grades)
names = columns[0]
print names
# ('Morty', 'Rick', 'Jerry', 'Kramer')


Extra Credit: Unzipping

额外学分:解压缩

zip(*args)is called “unzipping” because it has the inverse effect of zip

zip(*args)被称为“解压缩”,因为它具有相反的效果 zip

numbers = (1,2,3)
letters = ('a','b','c')

zipped = zip(numbers, letters)
print zipped
# [(1, 'a'), (2, 'b'), (3, 'c')]

unzipped = zip(*zipped)
print unzipped
# [(1, 2, 3), ('a', 'b', 'c')]
  • unzipped: tuple_1 = e1 of each zipped tuple. tuple_2 = e2 of each zipped
  • unzipped: tuple_1 = 每个压缩元组的 e1。tuple_2 = 每个的 e2zipped


Footnotes

脚注

  1. An object capable of returning its members one at a time (ex. list [1,2,3], string 'I like codin', tuple (1,2,3), dictionary {'a':1, 'b':2})
  2. {key1:value1, key2:value2...}
  3. “Unpacking” (*)
  1. 能够一次返回一个成员的对象(例如列表 [1,2,3]、字符串 'I like codin'、元组 (1,2,3)、字典 {'a':1, 'b' :2})
  2. {key1:value1, key2:value2...}
  3. “开箱”(*)

*Code:

*代码:

# foo - function, returns sum of two arguments
def foo(x,y):
    return x + y
print foo(3,4)
# 7

numbers = [1,2]
print foo(numbers)
# TypeError: foo() takes exactly 2 arguments (1 given)

print foo(*numbers)
# 3

*took numbers(1 arg) and “unpacked” its' 2 elements into 2 args

*numbers(1 arg) 并将其 2 个元素“解包”为 2 个 args

回答by Ankur Kothari

I don't think zipreturns a list. zipreturns a generator. You have got to do list(zip(a, b))to get a list of tuples.

我不认为zip返回一个列表。zip返回一个生成器。你必须list(zip(a, b))得到一个元组列表。

x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
list(zipped)

回答by Hamidreza

In Python 3zipreturns an iterator instead and needs to be passed to a list function to get the zipped tuples:

Python 3 中,zip返回一个迭代器,需要传递给一个列表函数来获取压缩的元组:

x = [1, 2, 3]; y = ['a','b','c']
z = zip(x, y)
z = list(z)
print(z)
>>> [(1, 'a'), (2, 'b'), (3, 'c')]

Then to unzipthem back just conjugate the zipped iterator:

然后unzip他们回来只是共轭压缩迭代器:

x_back, y_back = zip(*z)
print(x_back); print(y_back)
>>> (1, 2, 3)
>>> ('a', 'b', 'c')

If the original form of list is needed instead of tuples:

如果需要原始形式的列表而不是元组:

x_back, y_back = zip(*z)
print(list(x_back)); print(list(y_back))
>>> [1,2,3]
>>> ['a','b','c']

回答by Micheal J. Roberts

It's worth adding here as it is such a highly ranking question on zip. zipis great, idiomatic Python - but it doesn't scale very well at all for large lists.

值得在这里添加,因为它是 zip 上排名如此高的问题。zip是伟大的、惯用的 Python - 但对于大型列表,它根本不能很好地扩展。

Instead of:

代替:

books = ['AAAAAAA', 'BAAAAAAA', ... , 'ZZZZZZZ']
words = [345, 567, ... , 672]

for book, word in zip(books, words):
   print('{}: {}'.format(book, word))

Use izip. For modern processing, it stores it in L1 Cache memory and is far more performant for larger lists. Use it as simply as adding an i:

使用izip. 对于现代处理,它将它存储在 L1 缓存内存中,并且对于更大的列表性能更高。使用它就像添加一个i

for book, word in izip(books, words):
   print('{}: {}'.format(book, word))