2021年5月8日 星期六

python dict & list comprehension sample

 a = '''

Tomorrow Will Be Better

The Holdup

At first he was sly

He was opening doors

Making sure that you know you're adored

Making out in his Honda Accord

You never felt this way before

But things change since the first date

Think back on when he was great

So sad 'cause he's always late

Lose time not pounds when you're overwaiting

You're overdating

Think man is satan

Growing impatient

You're done participating

You think you lost him

But never had him

I'm sorry that you think you're permanently damaged

I promise it gets better if you wait so

Don't give up on that boy who's got a halo

You opened up your heart to have it broken

Don't let it scar you so bad you can't leave it open

The bar will always be there when you need it

But taking shots won't help erase how you were treated

I promise it gets better if…

'''

#sol 1

ab = a

a = [i.lower() for i in a if i.lower()>='a' and i.lower() <='z' ]

s = list(set(a))

s.sort()

for i in s:

    print(str(i)+':'+str(a.count(i)))

 

print()

#sol 2

ab = [i.lower() for i in ab if i.lower() >= 'a' and i.lower()<='z' ]   

charCounts = {}

for char in ab:

    if char.lower() in charCounts:

        charCounts[char.lower()] += 1

    else:

        charCounts[char.lower()]=1

key_list = list(charCounts.keys())

key_list.sort()


for key in key_list:

    print(key,':',charCounts[key])

沒有留言: