该项目是使用特定算法将项目分类到框中。在将每个项目分配给适当的类,返回到另一个函数以及使用和修改数据类的对象内保存的数据后,我遇到了麻烦。
我的测试文件如下:
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函数。功能。
答案 0 :(得分: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))
答案 1 :(得分:0)
我要做的不是使用字典,而是使用列表将数据传递给新函数。
文本文件->列表->字典->列表-> sortedList
这是我新的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