[英]How does the python range command work with lists?
大家好,我在这里遇到这个问题,我真的无法弄清楚问题出在哪里。 我知道range(2)为可能的i给出了0和1。 len(R)=2。列表从0开始。
R = [[1,1],[5,5]]
for i in range(len(R)):
if R[i][0] == R[i][1]:
R.remove(R[i])
错误:
if R[i][0] == R[i][1]:
IndexError: list index out of range
R = [[1,1],[5,5]]
R = [x for x in R if x[0] != x[1]]
应该是!=而不是==,因为他想获取不相同的数字。
通常,迭代列表中的项目要容易得多:
Removal_items =[]
for I in R:
#I is now a variable that represents the object in the list, or I = R[0]...R[n] where n = len(r) -1
if I[0] == I[1]:
Removal_items.append(I)
for I in Removal_items:
R.remove(I)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.