假设我的字典如下:
class Airplane:
def __init__(self, colour, Airplane_type):
self.colour = colour
self.Airplane_type = Airplane_type
def is_Airplane(self):
return self.Airplane_type=="Jet"
def is_orange(self):
return self.colour=="orange"
class Position:
def __init__(self, horizontal, vertical):
self.horizontal = int(horizontal)
self.vertical = int(vertical)
from airplane import Airplane
from position import Position
Class test():
def __init__(self):
self.landings:{Position(1,0) : Airplane("Jet", "orange"),
Position(3,0) : Airplane("Boeing", "blue"),}
例如,如何提取所有橙色飞机并返回橙色飞机的数量。你知道吗
此代码应提供所需的结果:
请注意,
len
在许多情况下适用于列表或字典中的x数。你知道吗一种优雅的方法是列出理解:
正如M.K.Hunter所说,您可以调用列表中的len()来获取号码。你知道吗
如果你想找到橙色飞机的位置,你可能想迭代字典的
items
,这样你既可以测试飞机的颜色,又可以同时看到位置:如果您使用的是python2,并且在
self.landings
字典中有许多值,那么最好使用iteritems
,而不是直接使用items
(后者在python3中总是最好的)。你知道吗请注意,如果此查询是您希望经常执行的操作,那么使用其他字典组织可能是有意义的。不是按位置索引,而是按平面颜色索引,并将位置存储为
Airplane
实例的属性。你知道吗相关问题 更多 >
编程相关推荐