Dictionary Counter Problem

fhandle=open("mbox.txt")
dct=dict()
lst= list()

for line in fhandle:
	if line.startswith("From "):
		words=line.split()
		lst.append(words[2])
		for count in lst:
			if not count in dct:
				dct[count]=1
			else:
				dct[count]+=1
	else:
		continue

print(dct)

Arkadaşlar merhaba, Python’da yeniyim ve sözlükler üzerinde çalışıyorum.
Örnek şu şekildeydi: Write a program that categorizes each mail message by which day
of the week the commit was done. To do this, look for lines that start with
“From”, then look for the third word and keep a running count of each of the
days of the week. At the end of the program, print out the contents of your
dictionary (order does not matter).
{‘Fri’: 20, ‘Thu’: 6, ‘Sat’: 1}

Cevap üstteki gibi çıkmalıyken benim programımda: {‘Sat’: 27, ‘Fri’: 330, ‘Thu’: 21} olarak alıyorum. Bunun sebebini anlayamadım. Yardımcı olabilirseniz çok sevinirim.

mbox.txt dosyası:https://www.py4e.com/code3/mbox-short.txt

Merhaba,

lst isimli liste üzerinde çalışan for döngüsü, sözlükteki anahtarların değerlerini yükseltmek için her seferinde tekrar tekrar çalışıyor. words = line.split()'den sonraki kısmı silin yerine aşağıdakileri yazın, sorun düzelir. lst isimli listeye de burada gerek yok.

        if words[2] not in dct:
            dct[words[2]] = 1
        else:
            dct[words[2]] += 1

Ayrıca else: continue yazmanıza da gerek yok.

1 Beğeni