簡體   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