【问题标题】:Properly using dataclasses to return values of items正确使用数据类返回项目的值
【发布时间】:2018-10-30 05:01:19
【问题描述】:

该项目是使用特定算法将项目分类到盒子中。在将每个项目分配给适当的类后,我遇到了麻烦,以返回另一个函数并使用和修改数据类中对象中保存的数据。

我的测试文件如下所示:

17 10 4
Abacus 3
Blender 5
Chessboard 3
Dishes 6

我的课:

@dataclass
class InventoryItem:
    name: str
    weight: float


@dataclass
class BoxInventory:
    name: str
    maxWeight: float
    remainingWeight: float
    contents: dict = ""
    """
    def listContents(self, contents):
        self.listContents = contents

    def remainingWeight(self, remainingWeight):
        self.remainingWeight = remainingWeight

    def addItemWeight(self, itemWeight):
        self.remainingWeight -= itemWeight

    def addItemList(self, itemName, itemWeight, contents):
        self.contents = contents[itemName] = contents[itemWeight]
    """

这是我读取文本文件并将其传输到班级的地方:

"""
Take the given txt file and format into proper list for boxes and items
:param filename: The filename of the text file
:return: Send lists to to be used by an algo.
"""
with open(filename, 'r') as myFile:  # Open the correct file
    itemDict = {}
    boxDict = {}

    myList = [line.split() for line in myFile.readlines()]
    boxLine = ' '.join(myList[0])

    for line in range(1, len(myList)):
        lines = ''.join(myList[line])
        itemName = lines[:-1]
        weight = lines[len(lines) - 1:]

        item = InventoryItem(itemName, int(weight))
        itemDict[itemName] = [item]

    boxString = ""
    count = 0
    for char in boxLine:
        if char != " ":
            boxString = boxString + char
        else:
            boxName = "Box" + str(count)
            box = BoxInventory(boxName, int(boxString), int(boxString))
            boxDict[boxName] = [box]
            boxString = ""
            count += 1

myReturn = {}
myReturn['boxDict'] = boxDict
myReturn['itemDict'] = itemDict
return myReturn

未实现的算法:

def roomiest(myReturnDict):
    """
    For each item find the box with the greatest remaining allowed weight that can support the item and place the item in that box
    :param boxList: The list of boxes in the class from the given file
    :param itemList: The list of items in the class from the given file
    :return: If boxes were able to fit all items(1); items in box with individual weights(2); Box name with max
    weight(3); items with their weights that were left behind(4)
    """
    itemList = myReturnDict.get("itemDict")
    boxList = myReturnDict.get("boxDict")

我的问题是我确实知道如何从我的 我的算法中的 fileReader 函数。函数。

【问题讨论】:

    标签: python-3.x python-dataclasses


    【解决方案1】:

    您的输入函数有点奇怪,因为您将对象存储在字典中长度为 1 的列表中。所以你的数据看起来像:

    'Dishes': [InventoryItem(name='Dishes', weight=6)]
    

    而不是

    'Dishes': InventoryItem(name='Dishes', weight=6)
    

    您可能有这样做的原因,但是将 itemDict[itemName] = [item] 更改为 itemDict[itemName] = item 会使您的代码更容易理解(boxDict[boxName] = [box] 也是如此)。通过该更改,您可以使用以下内容轻松访问已解析的数据:

    for item_name, item in itemList.items():
        print(item.name)
        print(item.weight)
    

    这将遍历 itemList 字典,获取键、值对,在本例中为 itemName、item(或原始代码中的 [item]。如果您不想更改它,请将 item 替换为 item[0 ] 在上面的代码中)。然后你可以通过调用它们的标签直接访问你的类的属性。

    你可以得到剩余空间最多的盒子,使用

    sorted_box_list = (sorted(boxList.values(), key=operator.attrgetter('remainingWeight'), reverse=True))
    

    【讨论】:

      【解决方案2】:

      我所做的不是使用字典,而是使用列表将数据传递给新函数。

      文本文件 --> 列表 --> 字典 --> 列表 --> 排序列表

      这是我的新 fileReader 函数:

      def fileReader(filename):
          """
          Take the given txt file and format into proper list for boxes and items
          :param filename: The filename of the text file
          :return: Send lists to to be used by an algo.
          """
          with open(filename, 'r') as myFile:  # Open the correct file
              itemList = []
              boxList = []
      
              myList = [line.split() for line in myFile.readlines()]
              boxLine = ' '.join(myList[0])
      
              for line in range(1, len(myList)):
                  lines = ''.join(myList[line])
                  itemName = lines[:-1]
                  weight = lines[len(lines) - 1:]
      
                  item = InventoryItem(itemName, int(weight))
                  itemList.append(item)
      
              boxString = ""
              count = 0
              for char in boxLine:
                  if char != " ":
                      boxString = boxString + char
                  else:
                      boxName = "Box" + str(count)
                      box = BoxInventory(boxName, int(boxString), int(boxString))
                      boxList.append(box)
                      boxString = ""
                      count += 1
      

      然后我使用相同的方法读取每个算法中的数据并对其进行排序:

      def roomiest(myReturnDict):
          """
          For each item find the box with the greatest remaining allowed weight that can support the item and place the item in that box
          :param boxList: The list of boxes in the class from the given file
          :param itemList: The list of items in the class from the given file
          :return: If boxes were able to fit all items(1); items in box with individual weights(2); Box name with max
          weight(3); items with their weights that were left behind(4)
          """
          itemData = list(myReturnDict.get("itemList"))
          boxData = list(myReturnDict.get("boxList"))
      
          sortedItemList = sorted(itemData, key=lambda x: x.weight, reverse=True)
          sortedBoxList = sorted(boxData, key=lambda x: x.remainingWeight, reverse=True)
              myReturn = {}
      
              myReturn['boxList'] = boxList
              myReturn['itemList'] = itemList
              return myReturn
      

      我的数据类如下所示:

      @dataclass
      class InventoryItem:
          name: str
          weight: float
      
      
      @dataclass
      class BoxInventory:
          name: str
          maxWeight: float
          remainingWeight: float
          contents: dict = ""
      
      
      def itemWeight(item):
          print("Weight of", item.name, "is: ", item.weight, "\n")
          return item.weight
      
      
      def remainWeight(box):
          print("Rem. weight in ", box.name, "is: ", box.remainingWeight, "\n")
          return box.remainingWeight
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-10-14
        • 2019-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多