从python词典中提取

2024-09-21 01:27:03 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我的字典如下:

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

例如,如何提取所有橙色飞机并返回橙色飞机的数量。你知道吗


Tags: selfreturninitisdeftypepositionclass
3条回答

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

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

请注意,len在许多情况下适用于列表或字典中的x数。你知道吗

一种优雅的方法是列出理解:

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

正如M.K.Hunter所说,您可以调用列表中的len()来获取号码。你知道吗

如果你想找到橙色飞机的位置,你可能想迭代字典的items,这样你既可以测试飞机的颜色,又可以同时看到位置:

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

如果您使用的是python2,并且在self.landings字典中有许多值,那么最好使用iteritems,而不是直接使用items(后者在python3中总是最好的)。你知道吗

请注意,如果此查询是您希望经常执行的操作,那么使用其他字典组织可能是有意义的。不是按位置索引,而是按平面颜色索引,并将位置存储为Airplane实例的属性。你知道吗

相关问题 更多 >

    热门问题