简体   繁体   中英

extract from python dictionary

Lets say my dictionary is the following:

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

How do I extract all the orange airplanes and return the number of orange planes for instance.

An elegant way of doing this would be with a list comprehension:

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

As MK Hunter said, you can call len() on the list to get the number.

This code should give you the result you want:

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

Note that len will work in many situations for the number of x in a list or dictionary.

If you want to find the position of the orange airplanes, you probably want to iterate over the items of the dictionary so that you can both test the color of the plane and at the same time see the position:

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

If you're using Python 2 and you have many values in the self.landings dictionary, it might be better to use iteritems rather than items directly (the latter is always best in Python 3).

Note that if this query is something you expect to do frequently, it might make sense to use a different dictionary organization. Rather than indexing by position, index by plane color and store the position as an attribute of the Airplane instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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