实现以下目标的pythonic方式是什么?
从:
a = [('apple', 10), ('of', 10)]
b = [('orange', 10), ('of', 7)]
获取
c = [('orange', 10), ('of', 17), ('apple', 10)]
答案 0 :(得分:3)
你基本上有字对计数器。使用// - get the FileGroupDescriptor structure
HGLOBAL hg=pDataObject->GetGlobalData(cfDescriptor);
LPFILEGROUPDESCRIPTOR pfgd=(LPFILEGROUPDESCRIPTOR)::GlobalLock(hg);
// - get a CFile abstraction of the actual data
FORMATETC etcFileContents={ cfContent, NULL, DVASPECT_CONTENT, 0, TYMED_ISTREAM }; // 0 = first dropped file
CFile *f=pDataObject->GetFileData( cfContent, &etcFileContents );
// Problem: "f" created but CFile::m_hFile equals INVALID_HANDLE_VALUE
// - read one sample byte
BYTE b;
f->Read(&b,1);
// - delete the file object
delete f;
可以让你以自然的Pythonic方式处理它们:
collections.Counter()
另见Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?
演示:
from collections import Counter
c = (Counter(dict(a)) + Counter(dict(b))).items()
您可以放弃>>> from collections import Counter
>>> a = [('apple', 10), ('of', 10)]
>>> b = [('orange', 10), ('of', 7)]
>>> Counter(dict(a)) + Counter(dict(b))
Counter({'of': 17, 'orange': 10, 'apple': 10})
>>> (Counter(dict(a)) + Counter(dict(b))).items()
[('orange', 10), ('of', 17), ('apple', 10)]
来电,并在此处继续使用.items()
。
您可能希望避免构建(单词,计数)元组,并从一开始就使用Counter()
个对象。