Mah*_*led 0 python list unique
嘿,我试图从列表中删除一个项目(不使用set):
list1 = []
for i in range(2,101):
for j in range(2,101):
list1.append(i ** j)
list1.sort()
for k in range(1,len(list1) - 1):
if (list1[k] == list1[k - 1]):
list1.remove(list1[k])
print "length = " + str(len(list1))
Run Code Online (Sandbox Code Playgroud)
该set函数工作正常,但我想应用此方法.除了我得到:
IndexError: list index out of range
Run Code Online (Sandbox Code Playgroud)
在声明中:
if (list1[k] == list1[k - 1]):
Run Code Online (Sandbox Code Playgroud)
编辑添加 (感谢Ned Batchelder)工作代码是:
list1 = []
for i in range(2,101):
for j in range(2,101):
list1.append(i ** j)
list1.sort()
k = 0
while k < len(list1) - 1: # while loop instead of for loop because "The range function is evaluated once before the loop is entered"
k += 1
if (list1[k] == list1[k - 1]):
list1.remove(list1[k])
list1.sort()
k -= 1 # "If you find a duplicate, you don't want to move onto the next iteration, since you'll miss potential runs of more than two duplicates"
print "length = " + str(len(list1))
Run Code Online (Sandbox Code Playgroud)
您的代码不起作用,因为在循环中,您正在迭代原始列表中的所有索引,但会缩短列表.在迭代结束时,您将访问不再存在的索引:
for k in range(1,len(list1) - 1):
if (list1[k] == list1[k - 1]):
list1.remove(list1[k])
Run Code Online (Sandbox Code Playgroud)
该range功能一旦进入循环之前进行评估,从而在列表中的所有索引列表.每次调用都会remove将列表缩短一次,因此如果删除任何元素,则可以保证在列表末尾出现错误.
如果你想使用这样的循环,请尝试:
k = 1
while k < len(list1):
if list1[k] == list1[k-1]:
del list1[k]
else:
k += 1
Run Code Online (Sandbox Code Playgroud)
我修了一些其他的东西:
| 归档时间: |
|
| 查看次数: |
473 次 |
| 最近记录: |