[英]Given a list of [string, number] tuples, create a dictionary where keys are the first characters of strings and the values are sums of the numbers
I have a list of tuples, where first object is a string and second one is a number.我有一个元组列表,其中第一个 object 是一个字符串,第二个是一个数字。 I need to create a dictionary with using first letter of the string as a key and number (or I need to add some numbers if keys will be the same) as a value.
我需要创建一个字典,使用字符串的第一个字母作为键和数字(或者如果键相同,我需要添加一些数字)作为值。 for example:
例如:
input输入
lst = [('Alex', 5), ('Addy', 7), ('Abdul', 2), ('Bob', 6), ('Carl', 8), ('Cal', 4)]
output output
dct = {'A': 14, 'B': 6, 'C': 12}
The most simple, straightforward and naive way is:最简单、直接和幼稚的方法是:
dct = {}
for k, v lst:
if k in v:
dct[k] += v
else:
dct[k] = v
There are ways to progressively be more clever, the first is probably to use .get
with the default:有一些方法可以逐渐变得更聪明,第一种可能是使用
.get
和默认值:
dct = {}
for k, v in lst:
dct[k] = dct.get(k, 0) + v
Finally, you can use a collections.defaultdict
, which takes a "factory" function which will be called if the key is not there, use int
as the factor:最后,您可以使用
collections.defaultdict
,它采用“工厂” function 如果密钥不存在将被调用,使用int
作为因素:
from collections import defaultdict
dct = defaultdict(int)
for k, v in lst:
dct[k] += v
NOTE: it is usually safer to create a regular dict out of this, to avoid the default behavior:注意:创建一个常规的字典通常更安全,以避免默认行为:
dct = dict(dct)
Or even甚至
dct.default_factory = None
Finally, one of the more flexible ways is to create your own dict
subclass and use __missing__
, this is useful if need access to the key when you are making the default value, so not particularly more helpful here, but for completion's sake:最后,一种更灵活的方法是创建自己的
dict
子类并使用__missing__
,如果在设置默认值时需要访问键,这很有用,所以在这里不是特别有用,但为了完成:
class AggDict(dict):
def __missing__(self, key):
return 0
dct = AggDict()
for k, v in dct:
dct[k] += v
Use a defaultdict
:使用
defaultdict
:
dct = defaultdict(int) # default to 0
for name, val in lst:
dct[name[0]] += val
dct = dict(dct) # get rid of default value
You could use Counter from collections to convert the tuples to countable key/values, then use reduce from functools to add them together:您可以使用 collections 中的 Counter 将元组转换为可计数的键/值,然后使用 functools 中的 reduce 将它们相加:
from collections import Counter
from functools import reduce
lst = [('Alex', 5), ('Addy', 7), ('Abdul', 2), ('Bob', 6), ('Carl', 8), ('Cal', 4)]
dst = reduce(Counter.__add__,(Counter({k[:1]:v}) for k,v in lst))
# Counter({'A': 14, 'C': 12, 'B': 6})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.