我有一本列表字典,上面写着:
dic = {"foo" : [1,3,5,6] , "bar" : [5, 3, 8, 4]}我正在尝试创建一个与这些列表相反的新字典,同时又不破坏原来的字典
我甚至尝试过像这样的东西
list1 = dic["foo"]
list2 = list1.reverse()
newDic = {}
newDic["foo"] = list2但看起来dic["A"]、list1和list2都指向相同的内存位置。换句话说,在这个过程中,dic["foo"]也被颠倒了,这不是我想要的!有什么简单的方法可以解决这个问题吗?
发布于 2014-10-27 14:27:14
如果你想看整本字典,试试下面这一行:
newDic = {key:value[::-1] for key,value in dic.iteritems()}
如果你只想做一个列表,试试这个:
list1 = dic["foo"]
newDic = {}
newDic["foo"] = list1[::-1]list.reverse()将更改列表本身。尝试list[::-1],它将返回一个反转列表的新副本
发布于 2014-10-27 14:27:18
list1.reverse()是一种就地逆转。请改用函数reversed(list1),该函数不会修改调用该函数的列表。
具体地说:
dic = {"foo" : [1,3,5,6] , "bar" : [5, 3, 8, 4]}
list1 = dic["foo"]
list2 = list(reversed(list1))
newDic = {}
newDic["foo"] = list2注意,reversed(list1)返回一个generator,而您想要完整的列表,这就是上面调用list的原因。
发布于 2014-10-27 14:31:41
问题出在list2 = list1.reverse()
list.reverse()方法将颠倒相同的列表。
喜欢
>>> a = [66.25, 333, 333, 1, 1234.5]
>>> a.reverse()
>>> a
[1234.5, 1, 333, 333, 66.25]reverse的返回类型为None
>>> a = [66.25, 333, 333, 1, 1234.5]
>>> b = a.reverse()
>>> b
>>> print b
None所以在你的例子中,list2 = None。
另一个问题是
您正在访问f00,密钥为foo
https://stackoverflow.com/questions/26582136
复制相似问题