Python字典矩阵 "representation"

标签 python python-3.x

我有一个 Python 字典 dict。 想象一下这个简单的例子。字典:

bin1:{apple,apple,cherry,cherry,cherry,banana,banana,avocado}
bin2:{cucumber,cucumber,cucumber,cucumber,apple}
bin3:{cherry,cherry,banana,banana}

我想计算并存储它(以任何表示形式,我只是无法想出数据结构):

enter image description here

行代表所有键,列代表所有字典值中所有可用的不同水果

数字的意思是:对于每个键,我们计算该键出现水果的次数除以该键出现最多的其他特定水果的次数。

例如:对于 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/

相关文章:

按属性比较两个无序列表的 Pythonic 方法

python - 循环行并将数据打印到新数据框

python - 使用 Celery 在部分任务中使用位置参数的链组

Python:如何查看 Unix 时间戳是在一天中的某个时间之前还是之后

python-3.x - 判断Python程序是否并行运行

python - 根据 python 列表中的出现情况移动文件

python - 为什么下面的模式程序没有给出所需的输出?

python - pd.read_csv 中的字符串行索引导致错误 "The label [1] is not in the [index]"

python - 代码在 Thonny 中工作正常,但在终端中工作不正确。零售价格指数

python - 当我使用 HttpResponseRedirect 时,我得到 TypeError : quote_from_bytes() expected bytes in Django