那么,我有一个列表,看起来像这样:
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...
我希望使用一个类函数来得到这样的结果:
[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]
接下来,我希望删除缺少元素的部分:
[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]
对于产品4,订单已经更改。还有其他类似产品4的产品,也出现了故障(它们出现故障的方式也不同)
我已经为"课堂"做了一些准备,但是我不确定从这里开始做什么:
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
谁能展示Python代码来做这件事?提前谢谢你。
答案很明显,不是吗?我觉得你把事情弄得太复杂了。
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)
输出:
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$