我有一个 Python 字典 dict。 想象一下这个简单的例子。字典:
bin1:{apple,apple,cherry,cherry,cherry,banana,banana,avocado}
bin2:{cucumber,cucumber,cucumber,cucumber,apple}
bin3:{cherry,cherry,banana,banana}
我想计算并存储它(以任何表示形式,我只是无法想出数据结构):
行代表所有键,列代表所有字典值中所有可用的不同水果
数字的意思是:对于每个键,我们计算该键出现水果的次数除以该键出现最多的其他特定水果的次数。
例如:对于 bin1:樱桃出现次数最多 (3),因此苹果为 2/3(苹果出现 2 次除以樱桃出现 3 次),依此类推。
也许我们可以在字典中创建类似字典的东西:
bin1:{apple:2/3,banana:2/3,cherry:1,cucumber:0,avocado:1/3}
bin2:{apple:1/4,banana:0,cherry:0,cucumber:1,avocado:0}
bin3:{apple:0,banana:1,cherry:1,cucumber:0,avocado:0}
最佳答案
这只是对列表的操作,因为您只需单独处理每一行。所以
row1 = ["apple", "apple", "cherry", "cherry", "cherry", "banana", "banana", "avocado"]
import collections
row1count = collections.Counter(row1)
max_per_row = max(row1count.values()) # for python2: wrap with float()
{x: y/max_per_row for (x, y) in row1count.items()}
结果是
{'apple': 0.6666666666666666, 'cherry': 1.0, 'banana': 0.6666666666666666, 'avocado': 0.3333333333333333}
这使用collections.Counter
来计算每个项目的出现次数。然后它确定最大值,并在字典理解中除以它。
关于Python字典矩阵 "representation",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52462757/