从列表中删除当前元素

时间:2014-02-24 00:39:55

标签: python list

我有这个清单。 keys = ['Messi','Neymar','Xavi','Iniesta']我想迭代列表以从列表中删除当前元素。对于上面的列表,我希望有类似的东西

Messi is out
['Neymar', 'Xavi', 'Iniesta']
Neymar is out
['Messi', 'Xavi', 'Iniesta']
Xavi is out
['Messi', 'Neymar', 'Iniesta']
Iniesta is out
['Messi', 'Neymar', 'Xavi']

这是我到目前为止的代码。它似乎不起作用

keys = ['Messi', 'Neymar', 'Xavi', 'Iniesta']
tmp_keys = keys
length = len(keys)
for player in keys:
   if player in tmp_keys:
       print player + " is out"
       print tmp_keys
       tmp_keys.remove(player)
       tmp_keys = keys

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:1)

在删除项目之前,您的代码似乎正在打印 tmp_keys 。我认为如果你改变这些陈述,它将会奏效。

复制列表的更好方法可能只是:

tmp_keys = list(keys)

正如tmp_keys = keys所说tmp_keys只是keys>>> a = [1,2,3] >>> b = a >>> print a [1,2,3] >>> print b [1,2,3] >>> b.append(4) >>> print a [1,2,3,4] >>> print b [1,2,3,4]

相同列表的另一个标记

示例:

from itertools import combinations

keys = ['Messi', 'Neymar', 'Xavi', 'Iniesta']

c = combinations(keys, 3)

>>> for i in c:
...     print i
('Messi', 'Neymar', 'Xavi')
('Messi', 'Neymar', 'Iniesta')
('Messi', 'Xavi', 'Iniesta')
('Neymar', 'Xavi', 'Iniesta')

for comb in c:
    for name in keys:
    if name not in comb:
        print "{0} is out".format(name)
        print list(comb) # without list() you will just get tuples

你也可以这样做:

Iniesta is out
['Messi', 'Neymar', 'Xavi']
Xavi is out
['Messi', 'Neymar', 'Iniesta']
Neymar is out
['Messi', 'Xavi', 'Iniesta']
Messi is out
['Neymar', 'Xavi', 'Iniesta']

<强>输出:

{{1}}

答案 1 :(得分:0)

您显然打印列表之前将其删除。您想要在删除它后打印它。您还应该复制列表,而不是使用=

keys = ['Messi', 'Neymar', 'Xavi', 'Iniesta']
tmp_keys = keys[:]
length = len(keys)
for player in keys:
  if player in tmp_keys:
    print player + " is out"
    tmp_keys.remove(player)
    print tmp_keys
    tmp_keys = keys[:]

http://docs.python.org/2/library/copy.html

Python中的赋值语句不复制对象,它们在目标和对象之间创建绑定。对于可变或包含可变项目的集合,有时需要一个副本,因此可以更改一个副本而不更改另一个副本。

由于list没有copy(),因此需要使用不同的方法来防止对tmp_keys的更改也影响键

作为例子

keys = ['a', 'b', 'c', 'd', 'e']
tmp_keys = keys

del tmp_keys(3)
print keys

输出:a b c e

tmp_keys = keys[:]
print tmp_keys
print keys

输出:

a b c e
a b c d e

答案 2 :(得分:-1)

使用过滤器命令:

filter( lambda x: x!='Messi', ['Messi', 'Neymar', 'Xavi', 'Iniesta'])
['Neymar', 'Xavi', 'Iniesta']