繁体   English   中英

Python字典有序对

[英]Python Dictionary Ordered Pairs

好的,我需要创建一个程序,该程序接受有序对除以空格,然后将其添加到字典中。

points2dict(["3 5"])  
{"3":"5"}

我如何使python识别第一个数字是键,第二个数字是值???

使用split

In [3]: pairs = ['3 5', '10 2', '11 3']

In [4]: dict(p.split(' ', 1) for p in pairs)
Out[4]: {'10': '2', '11': '3', '3': '5'}
values = [
    '3 5',
    '6 10',
    '20 30',
    '1 2'
]
print dict(x.split() for x in values)
# Prints: {'1': '2', '3': '5', '20': '30', '6': '10'}

对于您的简单示例,其中只有成对的数字,总是用空格隔开,不需要验证:

def points_to_dict(points):
    #create a generator that will split each string of points
    string_pairs = (item.split() for item in points)
    #convert these to integers
    integer_pairs = ((int(key), int(value)) for key, value in string_pairs)
    #consume the generator expressions by creating a dictionary out of them
    result = dict(integer_pairs)
    return result

values = ("3 5", ) #tuple with values
print points_to_dict(values) #prints {3: 5}

需要特别注意的是,这将为您提供整数键和值(我假设这就是您想要的,并且无论如何它都是一个更有趣的变换来说明)。 这也将比python循环甚至是内置的map都要好(延迟执行允许生成器堆叠而不是为中间结果分配内存)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM