当我正在整理一个列表时,我怎样才能获得当前项的id以引用它来列出方法?
xl = [1,2,3] # initial list
yl = [3,2] # list used to remove items from initial list
for x in xl[:]:
for y in yl:
if x == y:
xl.pop(x) # problem
break
print x, y
print xl
Run Code Online (Sandbox Code Playgroud)
在简单的例子中,我想循环遍历2个列表,当我找到类似的项目时,将其从列表1中删除.
在"#problem"评论的行中我应该使用什么而不是X?
PS:注意它是我正在迭代的副本.
这样做的一般方法是enumerate.
for idx, item in enumerate(iterable):
pass
Run Code Online (Sandbox Code Playgroud)
但对于您的用例,这不是非常pythonic的方式来做你似乎尝试的.应避免迭代列表并同时修改它.只需使用列表理解:
xl = [item for item in xl if item not in yl]
Run Code Online (Sandbox Code Playgroud)