python-3.x - 在python dict中计算相等的值(碰撞)
问题描述
这篇文章对我没有用post_link
所以我在这里问:
我有一个 python 字典:
a = {'Andres':234,'Paul':345,'Andres':675}
我有这个代码
def get_index(dict, a_string):
# Variable to store the result (updated after each iteration)
result = 0
#Variable to append the final result of each key in the dict
collisions =[]
for a_character in a_string:
# Convert the character to a number (using ord)
a_number = ord(a_character)
# Update result by adding the number
result += a_number
collisions.append(result)
# Take the remainder of the result with the size of the data list
list_index = result % len(data_list)
return collisions
这将返回一个字符串的 unicode,例如:
get_index(teste, 'Andres')
returns [605]
我想要的是为每个键传递我的 dict ,值代码计算每个字符串的 de unicode_sum 并将其附加到冲突中:
我试过了:
def get_index(dict):
for k,v in teste.items:
for a_character in a_string:
# Convert the character to a number (using ord)
a_number = ord(a_character)
# Update result by adding the number
result += a_number
collisions.append(result)
我想要得到的结果是:
get_index(a)
output: [605, 402, 605]
然后我可以通过做来计算碰撞次数len(collision) - set(collision)
解决方案
由于"Andres"
不能两次出现在您的字典中,我将打乱另一个实例的字母以表明您将获得以下两个结果605
:
>>> d = {"Andres": 234, "Paul": 345, "nAsedr": 675}
>>> collisions = [sum(map(ord, s)) for s in d]
>>> collisions
[605, 402, 605]
>>> len(collisions) - len(set(collisions))
1
这也适用于 a list
of strings、a tuple
of strings 和 a set
of strings(其中 aset
也不允许您拥有多个"Andres"
)。
推荐阅读
- sql-server - 仅在一个 SQL 数据库中创建用户的权限
- dll - CTest、CMake 和 MinGW:可执行文件构建,但无法运行,因为未找到新的 DLL
- vimeo - 选择较旧的视频以固定到个人资料页面
- xpath - 有没有一种特定的方法可以将 xpaths 写入 rapidminer 以进行网络爬取
- django - 应用程序标签不是唯一的,重复的:帐户
- makefile - 为什么我得到“Makefile:1:***缺少分隔符。停止。” 用“设置-e”?
- oracle - 调试模式下如何查看光标的值?
- java - 如何按属性值比较两个 Java 对象列表
- laravel - Laravel - 雄辩的关系有很多但也有一个?
- angular - NPM 包/角度:当应用程序在产品中运行时抑制警告