0

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

我的测试文件如下所示:

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 函数读取解析的数据。功能。

4

2 回答 2

0

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

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

这是我的新 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
于 2018-10-30T17:06:55.290 回答
0

您的输入函数有点奇怪,因为您将对象存储在字典中长度为 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))
于 2018-10-30T15:00:13.343 回答