python遍历列表并查找唯一身份用户

时间:2012-05-28 21:21:13

标签: python list python-2.7

我这里有一个脚本来抓取一个csv,在一个列中它只是名称颜色。

如何遍历列表并获取唯一项目(删除重复项)?

当前输出: 黑色, 蓝色, 蓝色, 红色, 红色, 绿色

所需的输出: 黑色, 蓝色, 红色, 绿色

在我的代码中,我以某种方式管理了一个继续循环。

#!/usr/bin/python
import csv
import sys
import argparse

# creates a text file of all the colors in pipe seperated format
# parsing command line options
parser = argparse.ArgumentParser(prog='desc', description=__doc__)
parser.add_argument('-i', '--input', help='Input file', nargs='?', type=argparse.FileType('r'), default=sys.stdin)
parser.add_argument('-o', '--output', help='Output file', nargs='?', type=argparse.FileType('w'), default=sys.stdout)
args = parser.parse_args(sys.argv[1:])
# Declare variables from input
inf, outf = args.input, args.output
outf = csv.writer(outf)

print 'Loading %s file into memory' % inf.name
data = []
needle = ''
for i, line in enumerate(csv.reader(inf).next()):
    needle = line[11]
    if len(data) == 0:
        data.append(needle)
        continue
    j = 0
    for j, item in enumerate(data):
        print item
        if needle == item:
            print 'match'
            continue
        else:
            print 'no match: appending item'
            data.append(item)
            continue

4 个答案:

答案 0 :(得分:4)

您可以使用set()。看看这个简单的例子,我想这就是你想要的:

>>> list1=[1,2,3,4,5,6]
>>> list2=[4,5,6,7,8,9]
>>> sett=set(list1).union(set(list2))
>>> print(sett)
{1, 2, 3, 4, 5, 6, 7, 8, 9}

答案 1 :(得分:2)

您实际上没有2个列表。您只有一个列表,行[11],如果您在添加到结果之前已经看过它,则在每行检查整个结果列表。这将给出O(n2)运行时间,如果你的列表更大,你会注意到它。已经建议设置符号:

data = set()
for row in csv.reader(inf).next():
    data.add(row[11])

唯一的缺点是这不稳定。如果您需要维持订单,则只需要几个额外的步骤。

data = []
for row in csv.reader(inf).next():
    data.append(row[11])

result = []
for entry in data:
    if entry not in result: result.append(entry)

答案 2 :(得分:1)

你能不能只使用set?

data = set()

for i, line in enumerate(csv.reader(inf)):
    if i == 0:
        continue
    data.add( line[11] )

在你的代码中我找不到你需要迭代2个循环的原因(?) 如果您需要列表,您只需将set转换为list:data = list(data)

答案 3 :(得分:0)

如何将列表转换为集合,并提取独特的项目:

a = set(list1)
b = set(list2)
unique_items = a - b #or b - a depending on how you define unique