我试图从一组惟一值构建dict作为键,并用压缩的元组列表来提供项。在
set = ("a","b","c")
lst 1 =("a","a","b","b","c","d","d")
lst 2 =(1,2,3,3,4,5,6,)
zip = [("a",1),("a",2),("b",3),("b",3),("c",4),("d",5)("d",6)
dct = {"a":1,2 "b":3,3 "c":4 "d":5,6}
但我得到了:
^{pr2}$以下是我目前为止的代码:
#make two lists
rtList = ["EVT","EVT","EVT","EVT","EVT","EVT","EVT","HIL"]
raList = ["C64G","C64R","C64O","C32G","C96G","C96R","C96O","RA96O"]
# make a set of unique codes in the first list
routes = set()
for r in rtList:
routes.add(r)
#zip the lists
RtRaList = zip(rtList,raList)
#print RtRaList
# make a dictionary with list one as the keys and list two as the values
SrvCodeDct = {}
for key, item in RtRaList:
for r in routes:
if r == key:
SrvCodeDct[r] = item
for key, item in SrvCodeDct.items():
print key, item
在
dict
s中,所有键都是唯一的,每个键只能有一个值。在解决这个问题最简单的方法是将字典的值设为
list
,以模拟所谓的多重映射。在列表中,有键映射到的所有元素。在编辑:
您可能想查看这个PyPI包:https://pypi.python.org/pypi/multidict
不过,在引擎盖下,它可能会像上面描述的那样工作。在
阿飞,没有什么内置的支持你所追求的。在
您可以使用^{} 方法来实现这一点:
它将返回
^{pr2}$my_dict
的值:或者,使用TigerhawkT3提到的^{} 。在
代码问题:您没有检查现有的
key
。每次执行SrvCodeDct[r] = item
操作时,都会用item
值更新r
键的上一个值。为了解决这个问题,您必须将if
条件添加为:然而,可以使用^{} (如TigerhawkT3所述)或使用^{} 方法来简化此代码:
你不需要这些。只需使用
collections.defaultdict
。在相关问题 更多 >
编程相关推荐