gpt4 book ai didi

python - 使用索引访问 zip 对象的值

转载 作者:太空宇宙 更新时间:2023-11-03 21:02:22 25 4
gpt4 key购买 nike

我试图了解如何访问 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' object has no attribute 'index'

有没有一种新的方法来执行相同的机制

最佳答案

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

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

points = list(zip(list1,list2))

关于python - 使用索引访问 zip 对象的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55644043/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com