[英]Python: Filtering and Printing tuples from a list of tuples
我有一个这样的元组列表:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.