简体   繁体   中英

I assigned values to a list of strings with a dictionary. How can I sum these values?

cards = ['2','3','4','5','6','7','8','9','10','J','Q','K']

d = {'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'J':10,'Q':10,'K':10}

How do I sum(cards)? Is it even possible -- I read that the dictionary only maps objects to other objects.

if cards variable contains the labels of the cards you want to add then you can write the following code:

sum_of_cards = sum([d[i] for i in cards] )

Just because it exists:

sum(map(lambda x: d[x], cards))

Or even nicer with what @Chris_Rands suggested:

sum(map(d.get, cards))

Or even this solution using __getitem__ :

sum(map(d.__getitem__, cards))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM