Let's say I have a list (or other iterable object) ['a','b','c','d']
. I have a dict
X
. I can sum them up in the naive way:
s = 0
for k in ['a','b','c','d']:
s += X[k]
But is there a more pythonic way?
你可以做:
s = sum(X[k] for k in ['a','b','c','d'])
Yes, by using the sum
function and a generator expression . You can even iterate over the characters of a string:
s = sum(X[k] for k in 'abcd')
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.