[英]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.