问题:Python中的邮政编码列表

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

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

这给了我三个列表,x1x2,和x3,每一个,比方说,大小为20。

现在,我这样做:

zipall = zip(x1, x2, x3)

但是,当我这样做时:

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

我得到20,这不是我期望的。我预计三个。我认为我做的事情根本上是错误的。

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.

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.


回答 0

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

你自己看:

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)]

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

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

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

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

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

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.


回答 1

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...

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

zip takes a bunch of lists likes

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.


回答 2

在Python 2.7中,这可能工作得很好:

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

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

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

In Python 2.7 this might have worked fine:

>>> 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>):

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

回答 3

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

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

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

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

>>> 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.


回答 4

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

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

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

输入项

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

输出(列表)

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

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

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

  1. n个元组的列表:n是最短参数(输入)的长度
    • len(数字)== 3 <len(字母)== 4→短= 3→返回3个元组
  2. 每个元组的长度= args的数量(元组从每个arg中获取一个元素)
    • args =(数字,字母); len(args)== 2→具有2个元素的元组
  3. i第元组=(element_i arg1,element_i arg2…,element_i arg n

边缘案例

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

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

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

压缩中!

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]
  • zip 是一种优雅,清晰,简洁的解决方案

2.打印表格中的列

“ *” [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')

额外信用:解压缩

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。元组_2 =每个e2zipped

脚注

  1. 一个能够一次返回其成员的对象(例如列表[1,2,3],字符串“ I like codin”,元组(1,2,3),字典{‘a’:1,’b’ :2})
  2. {key1:value1,key2:value2 …}
  3. “拆箱”(*)

* 码:

# 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

*拿了numbers(1个参数)并将其2个元素“拆包”为2个参数

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)

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)

  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)

Edge Cases

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

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

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

Zip in Action!

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

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]
  • zip is an elegant, clear, & concise solution

2. Print columns in a table

“*” [3] is called “unpacking”: 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

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

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” (*)

* 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


回答 5

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

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

对于列表

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

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

对于字典:

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

输出为:

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

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.

If you are not using IPython then just install it: “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')

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')]

回答 6

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')]

然后unzip返回给他们,只需将压缩的迭代器进行共轭即可:

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

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

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

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

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 unzip them back just conjugate the zipped iterator:

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']

回答 7

为了完整起见。

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

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

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')]

回答 8

我不认为会zip返回列表。zip返回一个生成器。您必须要做的list(zip(a, b))是获取元组列表。

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

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

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

回答 9

值得在这里添加,因为它是zip中一个如此高度排名的问题。zip很棒,惯用的Python-但是对于大型列表而言,它的伸缩性根本不好。

代替:

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

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

izip。对于现代处理,它将其存储在L1高速缓存中,对于较大的列表,它的性能要好得多。使用它就像添加一个i

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

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

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:

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。