So, I have a list that look some thing like this:
name=[["product 1",15,male,yes]
["product 2",10,female,yes]
["product 2",10,female,yes]
["product 3",none,female,yes]
["product 4",20,yes,male]]
and so on...
And I wish to use an class function to get the result like this:
[Item("product 1",15,"male","yes"),
Item("product 2",10,"female", "yes"),
Item("product 2",10,"female", "yes"),
Item("product 3",none,"female","no"),
Item('product 4",20,"male","yes")...so on]
Next I wish to remove part where there is a missing element:
[Item("product 1",15,"male","yes"),
Item("product 2",10,"female", "yes"),
Item("product 2",10,"female", "yes"),
Item('product 4",20,"male","yes")...so on]
For product 4 the order have been changed. There are others like product 4, out of order as well (the way they are out of order different as well.)
I have done some preparation for the "class", but I am not sure what to do form here:
class Item():
__name = ""
__cost = 0
__gender = ""
__prime = ""
def __init__(self, name, cost, gender, prime):
self.__name = name
self.__cost = cost
self.__gender = gender
self.__prime = prime
Can anyone show the Python code to do it ? Thank you in advance.
The answer is pretty obvious, isn't it? I think you're making it harder that it needs to be.
timr@tims-gram:~/src$ cat x.py
name=[
["product 1",15,"male","yes"],
["product 2",10,"female","yes"],
["product 2",10,"female","yes"],
["product 3",None,"female","yes"],
["product 4",20,"male","yes"]
]
class Item():
_name = ""
_cost = 0
_gender = ""
_prime = ""
def __init__(self, name, cost, gender, prime):
self._name = name
self._cost = cost
self._gender = gender
self._prime = prime
def __repr__(self):
return f"Item({self._name},{self._cost},{self._gender},{self._prime})"
mylist = [Item(*k) for k in name if k[1]]
print(mylist)
Output:
timr@tims-gram:~/src$ python x.py
[Item(product 1,15,male,yes), Item(product 2,10,female,yes), Item(product 2,10,female,yes), Item(product 4,20,male,yes)]
timr@tims-gram:~/src$
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments