简体   繁体   English

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

[英]Python: Filtering and Printing tuples from a list of tuples

I have a list of tuples like this: 我有一个这样的元组列表:

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

Now I want only the tuples which don't have any numbers in the first index element of the tuple. 现在,我只想要在元组的第一个索引元素中没有任何数字的元组。 So my output from the above code should be like this: 所以我从上面的代码输出应该是这样的:

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

And I need to save the matr into a xls file. 我需要将matr保存到xls文件中。 I'm able to achieve this and print it to my console, but when I save the output, I get a few blank rows embedded in between the actual rows. 我可以实现并将其打印到控制台,但是当我保存输出时,我在实际行之间嵌入了一些空白行。 Please help! 请帮忙!

Here's my code: 这是我的代码:

    # 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')

This is my output on console: 这是我在控制台上的输出:

471 mistborn
2 nap
12 glare
2 diarrhea
14 wiping

But my xls output looks something like this: 但是我的xls输出看起来像这样:

Output with blank rows amidst actual rows 在实际行中输出空白行

I'm assuming the blank rows are coming in place of the removed tuples. 我假设空白行取代了删除的元组。 How to get an output without those blank rows? 如何获得没有那些空白行的输出? Please help! 请帮忙!

This could be for lines with count == 1 这可能适用于count == 1

This should fix it: 这应该解决它:

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  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM