python - 比较 2 个元素并循环 len(List)-1 时列表索引超出范围

标签 python list

我正在尝试比较 python 嵌套列表中的每个第一个元素,因此我决定循环 list-1 的长度以将元素与下一个元素进行比较,但我仍然得到“列表索引超出范围”。 难道不是应该比较第一个与第二个、第二个与第三个、第三个与第四个,总共 3 次交互吗?

A =[[1,2,3]
   ,[2,5,6]
   ,[5,2,3]
   ,[5,2,3]
   ]

S = len(A) - 1
for n in range(S):
    if(A[0][n]) == (A[0][n+1]):

        print("no")
    else:
        print('yes we did it')

最佳答案

你必须交换索引:

A =[[1,2,3]
   ,[2,5,6]
   ,[5,2,3]
   ,[5,2,3]
   ]
S = len(A) - 1
for n in range(S):
    if(A[n][0]) == (A[n+1][0]):
        print("no")
    else:
        print('yes we did it')

关于python - 比较 2 个元素并循环 len(List)-1 时列表索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57364613/

相关文章:

html - 为什么我的 <li> 类型没有显示?

python - 在 Python 中从 XML 创建字典列表

python - 比较 Python 列表

python - 在字符串列表 (Python) 中查找特定模式(正则表达式)

python - 复选框/组合框的 Tkinter 下拉列表

python - .read() 在 python 中使用askopenfilename() 返回 "unicode object has no attribute read"

python - 如何在不阻塞 python 计时器的情况下等待输入?

python - 我如何使用 GAE 和 Nosetest 模拟用户?

python - 是什么导致 Pandas 出现 "indexing past lexsort depth"警告?

python - python中的YUV子采样色度 channel