繁体   English   中英

从python字典中提取

[英]extract from python dictionary

可以说我的字典如下:

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"),}

我如何提取所有橙色飞机并返回例如橙色飞机的数量。

一个很好的方法是使用列表理解:

oranges = [plane for plane in self.landings.itervalues()
           if plane.is_orange()]

正如MK Hunter所说,您可以在列表上调用len()来获取数字。

此代码应为您提供所需的结果:

result = []
keys = []
for key in self.landings:
    if self.landings[key].color == "orange":
        result.append(self.landings[key])
        keys.append(key)
#at the end of the loop, "result" has all the orange planes
#at the end of the loop, "keys" has all the keys of the orange planes
number=len(result) #len(result) gives the number of orange planes

请注意,对于列表或字典中x的数量, len在许多情况下都适用。

如果要查找橙色飞机的位置,则可能要遍历字典中的items ,以便可以测试飞机的颜色并同时查看位置:

orange_plane_positions = [pos for pos, plane in self.landings.values()
                              if plane.is_orange()]

如果您使用的是Python 2,并且self.landings词典中有很多值,那么最好直接使用iteritems items而不是直接使用items (后者在Python 3中总是最好的)。

请注意,如果您希望经常执行此查询,则可以使用其他字典组织。 不用按位置索引,而是按平面颜色索引并将位置存储为Airplane实例的属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM