gpt4 book ai didi

python - 我可以相信 dict 的顺序在每次迭代时都保持不变吗?

转载 作者:太空狗 更新时间:2023-10-29 22:11:01 26 4
gpt4 key购买 nike

我有以下三个字符串(它们是独立存在的,但为了方便在这里显示在一起):

from mx2.x.org (mx2.x.org. [198.186.238.144])
by mx.google.com with ESMTPS id g34si6312040qgg.122.2015.04.22.14.49.15
(version=TLSv1 cipher=ECDHE-RSA-RC4-SHA bits=128/128);
Wed, 22 Apr 2015 14:49:16 -0700 (PDT)

from HQPAMAIL08.x.org (10.64.17.33) by HQPAMAIL13.x.x.org
(10.34.25.11) with Microsoft SMTP Server (TLS) id 14.2.347.0; Wed, 22 Apr
2015 17:49:13 -0400

from HQPAMAIL13.x.org ([fe80::7844:1f34:e8b2:e526]) by
HQPAMAIL08.iadb.org ([fe80::20b5:b1cb:9c01:aa86%18]) with mapi id
14.02.0387.000; Wed, 22 Apr 2015 17:49:12 -0400

我希望根据字符串的反向(从下到上)顺序用一些值填充字典。具体来说,对于每个字符串,我提取 IP 地址作为排序索引,然后提取完整的字符串作为值。

考虑到顺序很重要,我决定使用列表,并且最初做了这样的事情(伪代码,上面的一堆文本):

IPs =[]
fullStrings =[]
for string in strings:
IPs.append[$theIpAddressFoundInTheString]
fullstrings.append[$theWholeString]

产生以下两个列表(同样,只是一个例子):

IPs ['198.186.238.144', '10.64.17.33', 'fe80::7844:1f34:e8b2:e526']

fullstrings ['from mx2.x.org (mx2.x.org. [198.186.238.144])
by mx.google.com with ESMTPS id g34si6312040qgg.122.2015.04.22.14.49.15
(version=TLSv1 cipher=ECDHE-RSA-RC4-SHA bits=128/128);
Wed, 22 Apr 2015 14:49:16 -0700 (PDT)', 'from HQPAMAIL08.x.org (10.64.17.33) by HQPAMAIL13.x.x.org
(10.34.25.11) with Microsoft SMTP Server (TLS) id 14.2.347.0; Wed, 22 Apr
2015 17:49:13 -0400', 'from HQPAMAIL13.x.org ([fe80::7844:1f34:e8b2:e526]) by
HQPAMAIL08.x.org ([fe80::20b5:b1cb:9c01:aa86%18]) with mapi id
14.02.0387.000; Wed, 22 Apr 2015 17:49:12 -0400']

这在一定程度上一直运行良好,但现在当我开始使用这些列表中的值(在硬编码索引中)填充 dict 时,与其他列表中的值进行比较(同样在硬编码索引中)等等,不仅调试变得痛苦,代码变得不可持续。

我开始使用字典重写(返回一个字典,其中 IP 地址是键,完整的字符串是值)。然后我将执行如下操作:

for k,v in myDictOfIpsAndStrings:
anotherDict[$someHardcodedText] = k
anotherDict[$otherHardcodedText] = v

这是我的顾虑:我能确定字典在任何时候被迭代时总是按照创建字典的顺序完成吗?如果不能,这是我唯一的选择恢复到列表(以及繁琐且脆弱的长度比较、这样做固有的分配)等等?

我知道字典就其本质而言是未排序的。我知道 sorted 函数,但我不打算按任何降序/升序等对它们的键进行排序。而是关于维护(以某种方式)创建字典的顺序。

最佳答案

can I be sure that the dict, any time it is iterated over, will always be done in the order in which the dict was created?

不,dict 是无序的,并且会按照特定实现的决定安排其顺序。

>>> d = {3: 'c', 2: 'b', 1: 'a'}
>>> d
{1: 'a', 2: 'b', 3: 'c'}

看,在我创建 dict 之后,顺序立即改变了。

如果你想确保你有一个确定的、可控的顺序,你可以使用 collections.OrderedDict

>>> from collections import OrderedDict
>>> d = OrderedDict([(3, 'c'), (2, 'b'), (1, 'a')])
>>> d
OrderedDict([(3, 'c'), (2, 'b'), (1, 'a')])

您仍然可以按照您习惯的约定访问OrderedDict

>>> d[3]
'c'
>>> d.get(3)
'c'

请注意,您不必在创建时插入所有元素。如果需要,您可以一次插入一个。

>>> d = OrderedDict()
>>> d[3] = 'c'
>>> d[2] = 'b'
>>> d[1] = 'a'
>>> d[4] = 'd'
>>> d
OrderedDict([(3, 'c'), (2, 'b'), (1, 'a'), (4, 'd')])

关于python - 我可以相信 dict 的顺序在每次迭代时都保持不变吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30787056/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com