2021年5月8日 星期六

python list comprehension & dict

 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…

'''


# a = a.replace("'","")

ab = a


#sol 1

a = [i.lower() for i in a.split() if "'" not in i]

s = list(set(a))

s.sort()

for i in s:

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

print()


#sol 2

   

wCounts = {}

for w in a:

    if w.lower() in wCounts:

        wCounts[w.lower()] += 1

    else:

        wCounts[w.lower()]=1

k_list = list(wCounts.keys())

k_list.sort()


for k in k_list:

    print(k,':',wCounts[k])


output ----------------------------------

a:1

accord:1

adored:1

always:2

at:1

back:1

bad:1

bar:1

be:2

before:1

better:3

boy:1

broken:1

but:3

change:1

damaged:1

date:1

done:1

doors:1

erase:1

felt:1

first:2

gets:2

give:1

got:1

great:1

growing:1

had:1

halo:1

have:1

he:3

heart:1

help:1

him:2

his:1

holdup:1

honda:1

how:1

i:2

if:1

if…:1

impatient:1

in:1

is:1

it:6

know:1

late:1

leave:1

let:1

lose:1

lost:1

making:2

man:1

need:1

never:2

not:1

on:2

open:1

opened:1

opening:1

out:1

overdating:1

overwaiting:1

participating:1

permanently:1

pounds:1

promise:2

sad:1

satan:1

scar:1

shots:1

since:1

sly:1

so:3

sorry:1

sure:1

taking:1

that:3

the:3

there:1

things:1

think:4

this:1

time:1

to:1

tomorrow:1

treated:1

up:2

wait:1

was:3

way:1

were:1

when:3

will:2

you:11

your:1

沒有留言: