我有一个名为ShoppingList的类,我有一个购物清单列表。每个购物清单总会有3件事:第一件是水果,第二件是饮料,第三件是物品。
shopping_lists = [['apple', 'wine', 'napkins'],
['Avocado', 'soda', 'apron'], ['cherry', 'orange juice', 'knife']]
然后我创建了一个名为list_of_shopping_lists的新列表,它将使用上面的shopping_lists信息接收类ShoppingList的数组。
list_of_shopping_lists = []
for my_list in shopping_lists:
list_of_shopping_lists.append(shop_list.ShoppingList(
my_list[0],my_list[1],my_list[2])
如何在不通过列表[0],列表[1],列表[2]的情况下更好地创建此代码?
我的类ShoppingList如下:
class ShoppingList():
"""This Class provides a way to store shopping lists."""
# Creating constructor
def __init__(self, fruit, drink, obj):
self._fruit = fruit
self._drink = drink
self._object = obj
答案 0 :(得分:1)
就这样做 -
list_of_shopping_lists = []
for shoping_list in shopping_lists:
list_of_shopping_lists.append(shop_list.ShoppingList(*shoping_list))
答案 1 :(得分:1)
使用 Python 的参数解压缩:
shopping_lists = [['apple', 'wine', 'napkins'],
['Avocado', 'soda', 'apron'],
['cherry', 'orange juice', 'knife']]
class ShoppingList():
"""This Class provides a way to store shopping lists."""
# Creating constructor
def __init__(self, fruit, drink, obj):
self._fruit = fruit
self._drink = drink
self._object = obj
list_of_shopping_lists = [ShoppingList(*sh_list) for sh_list in shopping_lists]
print(list_of_shopping_lists)
示例输出:
[<__main__.ShoppingList object at 0x000000000420FF60>, <__main__.ShoppingList object at 0x0000000004F74E48>, <__main__.ShoppingList object at 0x0000000004F556D8>]
此外,避免使用list
或object
命名变量/属性以防止与Python的保留名称冲突
https://docs.python.org/3.4/tutorial/controlflow.html#arbitrary-argument-lists