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

2024-06-03 10:37:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个元组列表:

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

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

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

我需要把资料保存到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输出如下所示:

Output with blank rows amidst actual rows

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


Tags: inforifcountxlswordwritesheet
1条回答
网友
1楼 · 发布于 2024-06-03 10:37:05

这可能适用于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  

相关问题 更多 >