Python:从元组列表中过滤和打印元组



我有一个这样的元组列表:

lst = [(4, hen), (9, duck2), (45, soup), (87, Henry5)....]

现在我只想要元组的第一个索引元素中没有任何数字的元组。所以我从上面的代码输出应该是这样的:

matr = [(4, hen),(45, soup)]

我需要将 matr 保存到 xls 文件中。我能够实现这一点并将其打印到我的控制台,但是当我保存输出时,我在实际行之间嵌入了一些空白行。请帮忙!

这是我的代码:

    # Code generating some words into the list 'words'
    d = {}
    for w in words:
        if w in d:
            d[w] += 1
        else:
            d[w] = 1
    lst = [(d[w],w) for w in d]
    lst.sort(reverse=True)
    matr = {i for i in lst if not any(c.isdigit() for c in i[1])}
    workbook = xlwt.Workbook()
    sheet = workbook.add_sheet('test')
    sheet.write(0,0,'Index')
    sheet.write(0,1,"Word")
    sheet.write(0,2,"Count")       
    i = 1
    for count, word in matr:
        if count >1:
            print count, word.encode("utf-8")
            sheet.write(i, 0, i)
            sheet.write(i, 1, word)
            sheet.write(i, 2, count)
        i += 1    

    workbook.save(r'Dummy_4.xls')

这是我在控制台上的输出:

471 mistborn
2 nap
12 glare
2 diarrhea
14 wiping

但是我的 xls 输出看起来像这样:

在实际行中包含空白行的输出

我假设空白行代替了已删除的元组。如何在没有这些空白行的情况下获得输出?请帮忙!

这可能适用于带有count == 1的行

这应该可以解决它:

i = 1
for count, word in matr:
    if count >1:
        print count, word.encode("utf-8")
        sheet.write(i, 0, i)
        sheet.write(i, 1, word)
        sheet.write(i, 2, count)
        i += 1  

最新更新