Reputation: 105
I have a program that reads lines from a textfile, each line contains a word, such as price or product name. The program reads through all lines and saves each word in a list. Each product in the file contains of three lines, which are: product name, price and weight. So in the list will look like the following: ['Mjölk', '15 kr', '1 liter', 'Köttfärs', '80 kr', '1 kg', 'Morötter', '20 kr', '1 kg']
Now to the problem, I have the class:
class Produkt:
def __init__(self, produkt, pris, vikt):
self.produkt = produkt
self.pris = pris
self.vikt = vikt
I want to make Produkt objects from the items from the list, but I don't know how to loop through the items in the list and then save them as objects. I was thinking I'd make a list for the objects, and then like: for item in listofprodukts: objectlits.append(Produkt(item, item,item))
but this does obviously not work, anyone have an idea how to do this?
Upvotes: 1
Views: 86
Reputation: 3335
for i in range(len(listofprodukts)//3): #use xrange if it's python2
#// -> floor division. Will silently chop off excess if len(listofprodukts) isn't a multiple of 3
#print(listofprodukts[3*x:3*(x+1)]) # this expression makes chunks of three. Uncomment me to see :P
objectlits.append(Produkt(*listofprodukts[3*x:3*(x+1)]))
# ^This * is for argument unpacking
I'm using list slicing to bundle your list in groups of three. And because I'm lazy, I'm using argument unpacking to feed them into your object creator.
Admendum: I agree with TextGeek in that if you're going to do this type of thing, having some validation would be useful.
I'd personally put it in the model, but that's just me.
class Produkt:
def __init__(self, produkt, pris, vikt):
if not pris.endswith('kr'):
raise ValueError("Invalid price {}. Prices should be in kr".format(pris))
#raise ValueError, "Prices ..etc" for python 2
self.produkt = produkt
self.pris = pris
self.vikt = vikt
Upvotes: 2
Reputation: 41
Assuming the attribute order is consistent.
text_list = ['Mjolk', '15 kr', '1 liter', 'Kottfers', '80 kr', '1 kg', 'Morotter', '20 kr', '1 kg']
class Produkt: def init(self, produkt, pris, vikt): self.produkt = produkt self.pris = pris self.vikt = vikt
##make a representation of the Produkt object so we can verify we're getting what we want
def __repr__(self):
return_string = "|{}, {}, {}|".format(self.produkt, self.pris, self.vikt)
return(return_string)
object_list = [] ##create an empty object list index = 0 ##create an index variable and set it to 0
while index < len(text_list):
##Use the index to get this Produkt's produkt, pris, and vikt
produkt = text_list[index]
pris = text_list[index+1]
vikt = text_list[index+2]
##Create the new Produkt object
new_product = Produkt(produkt, pris, vikt)
##add the new product to the object list
object_list.append(new_product)
##Set the index to the next produkt in the list
index += 3
print(object_list) ##print the list objects to make sure we have what we want
Upvotes: 0
Reputation: 196
ProduktList =[]
for i in xrange(0,len(ListOfAllProuctsStuff),3)
ProduktList.append(Produkt(ListOfAllProuctsStuff[i],ListOfAllProuctsStuff[i+1],ListOfAllProuctsStuff[i+2])
Upvotes: 0
Reputation: 11075
assuming that the three attributes are consistently in order, you could simply iterate every third index and slice the list:
class Produkt:
def __init__(self, produkt, pris, vikt):
self.produkt = produkt
self.pris = pris
self.vikt = vikt
lst = ['Mjölk', '15 kr', '1 liter', 'Köttfärs', '80 kr', '1 kg', 'Morötter', '20 kr', '1 kg']
produkts = []
for i in xrange(0,len(lst),3): #in python 3.x use range() instead
produkts.append(Produkt(lst[i], lst[i+1], lst[i+2]))
Upvotes: 1
Reputation: 406
If you want to loop through try
For x in range(0 , 3):
You can change the three for amount of iterations you want. The example will do 3 iterations.
Upvotes: 0