0

我写了一些丢弃代码,它需要一个 id 列表检查重复项并写一个 id 列表。没什么特别的,只是我正在研究的一小部分..

我得到这个奇怪的输出。在我看来,分隔符在不应该的地方添加了空格。分隔符只是在单词或行之间吗?很困惑。

r s 9 3 6 4 5 5 4
r s 9 3 1 1 1 7 1 
r s 7 8 9 0 2 0 2 5 
r s 7 6 5 2 3 3 1 
r s 7 2 1 0 4 8 
r s 6 9 8 3 2 6 7 
r s 6 4 6 5 6 5 7
r s 6 2 9 2 4 2 
r s 6 1 9 9 1 1 5 6

代码:

__author__ = 'prumac'
import csv

allsnps = []

def open_file():
    ifile  = open('mirnaduplicates.csv', "rb")
    print "open file"
    return csv.reader(ifile)

def write_file():
    with open('mirnaduplicatesremoved.csv', 'w') as fp:
        a = csv.writer(fp, delimiter=' ')
        a.writerows(allsnps)


def checksnp(name):
    if name in allsnps:
        pass
    else:
        allsnps.append(name)

def mymain():
    reader = open_file()
    for r in reader:
        checksnp(r[0])
    print len(allsnps)
    print allsnps
    write_file()

mymain()
4

1 回答 1

3

.writerows()需要一个列表列表。相反,你给它一个字符串列表,这些被视为字符序列。

将每个字符串放在一个元组或列表中:

a.writerows([val] for val in allsnps)

请注意,您可以更有效地完成这一切:

with open('mirnaduplicates.csv', "rb") as ifile, \
     open('mirnaduplicatesremoved.csv', 'wb') as fp:
    reader = csv.reader(ifile)
    writer = csv.writer(fp, delimiter=' ')

    seen = set()
    seen_add = seen.add
    writer.writerows(row for row in reader if row[0] not in seen and not seen_add(row[0]))
于 2013-05-20T22:23:56.963 回答