使用其索引访问zip对象的值

时间:2019-04-12 03:23:31

标签: python

我试图了解如何访问zip对象,并且试图通过使用.index()来找出如何使用索引来访问压缩对象中的值,就像在Python 2中一样.x,但似乎在Python3中不起作用

这是代码

def find_neighbors(index):
    i, j = index
    print([(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)])
    return [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]

list1 = (211,209,210,210)
list2 = (72,72,73,71)
points = zip(list1,list2)

for i, index in enumerate(points):
    for x in find_neighbors(index):
          if x is not in points: continue
          j = points.index(x)

运行代码时,出现以下错误:AttributeError:'zip'对象没有属性'index'

在执行相同机制方面是否有新方法

3 个答案:

答案 0 :(得分:0)

似乎您希望points是一个列表,但是zip对象不是列表。

如果要将其转换为列表,请执行以下操作:

points = list(zip(list1,list2))

答案 1 :(得分:0)

Post::where("dispose_time", ">", now()->addMinutes(-10)->toDateTimeString())->delete(); 过去曾在Python 2中返回列表,但现在已成为Python 3中的生成器,因此您必须先使用zip构造函数将其转换为列表,然后才能使用{ {1}}方法:

list

答案 2 :(得分:0)

正如其他人所说:zip返回一个zip对象,它是一个迭代器,您可以使用它来生成其他内容,例如列表或字典。另外,(a,b,c)返回一个元组,而[a,b,c]返回一个列表。

>>> type((1,2,3))
<class 'tuple'>
>>> type([1,2,3])
<class 'list'>
>>> 

除非您要开始修改“列表”的内容,否则对您而言可能并不重要。您称它们为“列表”,所以我在下面列出了它们。无论哪种情况,一旦将它们压缩并转换为列表(list(zip(list1,list2)),您都会得到一个元组列表。实际上,这使您的代码更容易一些,因为您可以将元组传递给函数:

def find_neighbors(point):
i = point[0]
j = point[1]
print(f"List of neighbours of {point}: {[(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]}")
return [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]

list1 = [211,209,210,210,211]
list2 = [72,72,73,71,73]
pointsList = list(zip(list1,list2))

#These loops are just to show what is going on comment them out or delete them
for i in pointsList:
    print(i)
    print(f"The first element is {i[0]} and the second is {i[1]}")

#or let Python unpack the tuples - it depends what you want
for i, j in pointsList:
    print(i,j)

for point in pointsList:
print(f"In the loop for find_neighbours of: {point}")
for testPoint in find_neighbors(point):
    print(f"Testing {testPoint}")
    if testPoint not in pointsList:
        print(f"Point {testPoint} is not there.")
        continue
    elif testPoint in pointsList:
        print(f"*******************Point {testPoint} is there.***************************")

请注意,我已在您的数据中添加了一个邻居点,以便我们可以看到该函数找到了它。在对一条路径或另一条路径进行过多工作之前,请考虑一下列表和元组之间的区别。我的代码是用Python 3.7编写的。

最后,请记住,您可以使用字典pointDict = dict(zip(list1,list2)),它在程序中可能更有用,尤其是在您需要查找内容时。可能更pythonic。