从列表中检索元素:python

从列表中检索元素:python,python,Python,可能是一个非常天真的问题: 我有一份清单: color = ["red","blue","red","green","blue"] 现在,我想遍历这个列表 for c in color: # color is "red" get the rest of the colors except this red so rest = ["blue","red","green",blue"] 在下一次迭代中: c = blue rest = ["red","re

可能是一个非常天真的问题:

我有一份清单:

color = ["red","blue","red","green","blue"]
现在,我想遍历这个列表

for c in color:
   # color is "red"
     get the rest of the colors except this red
    so rest = ["blue","red","green",blue"]
在下一次迭代中:

    c = blue
    rest = ["red","red","green","blue"]
嗯。为什么我觉得这是一件非常琐碎的事情,而且可能有一个单行命令可以解决这个问题?
谢谢

考虑这一点最简单的方法是,您希望迭代每个长度小于列表的组合。为此,我们可以使用
itertools.combinations()

这给了我们:

('red', 'blue', 'red', 'green')
('red', 'blue', 'red', 'blue')
('red', 'blue', 'green', 'blue')
('red', 'red', 'green', 'blue')
('blue', 'red', 'green', 'blue')
这是一个很好的解决方案,因为它可以处理iterables和序列,可读性很强,应该很好而且很快

如果您还需要当前值,也可以很容易地获得,因为
combinations()
为您提供了一个可预测的顺序,所以我们只需使用
zip()
(当然,如果您希望获得最佳性能,请使用Python 2.x下的
itertools.izip()
,如
zip())
创建一个列表,而不是3.x)中的生成器

在这里,我反转了
comibinations()
的输入,使其从左到右工作-您可以在
zip()
中反转
color
,改为从右到左


因此,是的,简而言之,它是一个单行解决方案(如果计算导入数,则为两行)。

此Python代码将创建一个没有重复项的新输出列表

done = []
for c in color:
    if c in done:
        continue
    done.append(c)
    print c
切片和枚举可简化此任务:

>>> colors = ["red", "blue", "red", "green", "blue"]
>>> for i, color in enumerate(colors):
        rest = colors[:i] + colors[i+1:]
        print color, '-->', rest

red --> ['blue', 'red', 'green', 'blue']
blue --> ['red', 'red', 'green', 'blue']
red --> ['red', 'blue', 'green', 'blue']
green --> ['red', 'blue', 'red', 'blue']
blue --> ['red', 'blue', 'red', 'green']
跟踪每种颜色的位置,切片提取颜色前后的列表部分。

这也应该有效

for i in range(len(yourlist)):
    newlist = yourlist[:i] + yourlist[i:]

下面的示例将返回一个删除了重复项的列表。它从一个空的返回列表开始,检查颜色列表,如果输出中已经有颜色(本例中为红色),则忽略该颜色

#!/usr/bin/env python

color = ["red","blue","red","green","blue"]

def rem_dup(dup_list):
    corrected_list = []
    for color in dup_list:
        if color in corrected_list:
            continue
        else:
            corrected_list.append(color)

    return corrected_list
您可能会更好地使用以下内容

>>> set(color)
set(['blue', 'green', 'red'])
>>> 


删除重复项。两者都比for循环更有效。

您要查找list.pop()吗?它从列表中删除并返回一项。
combines()
的当前实现可能会给出一个可预测的顺序,但我不会指望它在将来的实现中保持不变。@spinlok组合的顺序是有保证的。@spinlok它是函数的一部分-改变它将是一个突破性的改变。@AshwiniChaudhary实际上,切片的速度比任何其他构建列表的方法都快(列表、l.extend和l[:]=s是相同的基础代码)。此外,切片将预先调整目标列表的大小,因此无需调整大小。瞧,你减1不仅是没有根据的,而且是完全不正确的。很抱歉评论不完整,我想说的是切片是一种更简单的方法,但是你的解决方案很慢,因为你用“+”添加了两个列表,这使得它很慢。我错了吗?@AshwiniChaudhary,不,不是。我不会基于不准确的知识进行向下投票。您的解决方案很慢,因为您正在使用
'+'
添加两个列表,我已使用
timeit
模块对其进行计时,请检查我的解决方案。可能很慢并不意味着太慢。我可能没有对答案投赞成票,但我认为没有理由投反对票。
for i in range(len(yourlist)):
    newlist = yourlist[:i] + yourlist[i:]
#!/usr/bin/env python

color = ["red","blue","red","green","blue"]

def rem_dup(dup_list):
    corrected_list = []
    for color in dup_list:
        if color in corrected_list:
            continue
        else:
            corrected_list.append(color)

    return corrected_list
>>> set(color)
set(['blue', 'green', 'red'])
>>> 
>>> import collections
>>> color = ["red","blue","red","green","blue"]
>>> collections.OrderedDict.fromkeys(color)
OrderedDict([('red', None), ('blue', None), ('green', None)])
>>>