Can';t访问Python对象的第二项
我有一个项目字典,列表的格式是 {(x,y):z,(x,y):z..}其中x和y是坐标,z是概率。我需要使用概率来执行操作。我如何访问这些 我试过这样的方法Can';t访问Python对象的第二项,python,object,Python,Object,我有一个项目字典,列表的格式是 {(x,y):z,(x,y):z..}其中x和y是坐标,z是概率。我需要使用概率来执行操作。我如何访问这些 我试过这样的方法 for item in lst: print item[1] 但是,这只返回y坐标。试图打印项目[2]时返回错误“需要两个以上的值才能解包”您可以使用以下方法: list = {(x1, y1): z1, (x2, y2): z2, ...} # actually a dict for (x, y), z in l
for item in lst:
print item[1]
但是,这只返回y坐标。试图打印项目[2]时返回错误“需要两个以上的值才能解包”您可以使用以下方法:
list = {(x1, y1): z1, (x2, y2): z2, ...} # actually a dict
for (x, y), z in list.items():
print x, y, z
或者这个:
list = {(x1, y1): z1, (x2, y2): z2, ...} # actually a dict
for z in list.values():
print z
但是您最好使用真正的列表
而不是命令
。最好不要给变量起与内置Python组件相匹配的名字,比如list
。那么你会有这样的东西:
lst = [(x1, y1, z1), (x2, y2, z2), ...]
for x, y, z in lst:
print x, y, z
在使用字典时,python可以分别检索名称和值。例如:
>>> a = {(1,2): 0.5, (2,3): 0.4}
>>> a.keys()
>>> [(1, 2), (2, 3)]
>>> a.values()
>>> [0.5, 0.4]
因此,您需要对概率进行计算:
for item in a.values():
print item
每个项目都将按顺序输出词典的值。首先,您没有lit,即dict,因此您可以使用坐标作为键访问z:
my_dict = {(x,y): z, (x,y):z...}
my_dict[(x, y)]
在for循环中:
for probability in my_dict.values():
print(probability)
我建议您不要为此使用名称列表,因为它是一个内置的如果您在这里展示的确实是您的数据结构{(x,y):z,(x,y):z..},那么您应该以另一种方式对其进行迭代和解压缩,而不是:
Python 3.6.3 (default, Oct 4 2017, 06:09:15)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.37)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> l = {(1,2):0.5, (3,4):0.9}
>>> for coordinates, probability in l.items():
... print(coordinates, probability)
...
(1, 2) 0.5
(3, 4) 0.9
看
如果需要元组列表,可以使用
>>> [ (coordinates, probabilities) for coordinates, probabilities in l.items() ]
[((1, 2), 0.5), ((3, 4), 0.9)]
在您的版本中,解包字典的键,它们是
x
坐标的tuple
和y
坐标print item[1]
引用y
坐标(python具有基于0
的索引),这不是您想要的。对于列表中的项,一次只获取一个项。那么,您如何访问第二项呢。这是我为你做的一个例子。假设这是你的字典d,坐标10,20的概率为0.1,坐标20,30的概率为0.2
d = {(10,20):0.1, (20,30):0.2}
d.items() # this will print- dict_items([((10, 20), 0.1), ((20, 30), 0.2)])
d[(10,20)] # this will print 0.1
d[(20,30)] # this will print 0.2
你们怎么说你们的数据在列表中?您能分享您的输入和期望吗?您需要阅读一本Python入门指南。另外,它是0索引的。。。“(x,y)”是
项[0],项[1]
也是一个dict,而不是列表。请参阅和