【问题标题】:How to impment Hashmap like data structures in Python如何在 Python 中实现类似 Hashmap 的数据结构
【发布时间】:2015-05-20 05:12:51
【问题描述】:

我是 python 的新手,需要一些帮助。我计划使用某种 hashMap 类型的数据结构来将字符串映射到它的长度。我如何在python中做到这一点?

【问题讨论】:

标签: python string hashmap


【解决方案1】:

使用空字典,如下所示:

string_lengths = {}

string = 'hello'

string_lengths[string] = len(string)

print string_lengths

输出:

{'hello': 5}

或者对字符串列表执行此操作:

string_lengths = {}

strings = ['Hello', 'There', 'Human Being']

for x in strings:
    string_lengths[x] = len(x)

print string_lengths

输出:

{'Human Being': 11, 'There': 5, 'Hello': 5}

请注意,字典是键值对的无序列表。

要引用字典中的项目:

string_lengths['Hello'] 返回5

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-08
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    • 2014-04-22
    相关资源
    最近更新 更多