这可能是一个非常简单的问题,之前可能已被问过,但这可能是我lacking vocabulary的一个问题,所以我提前道歉。
class Dog:
def __init__(self, name):
self.name = name
self.tricks = [] # creates a new empty list for each dog
def add_trick(self, trick):
self.tricks.append(trick)
d = Dog('Fido')
d.add_trick('roll over')
d.add_trick('fetch')
d.tricks
按预期返回:
['roll over', 'fetch']
但如果我再跑:
d.add_trick('play dead', 'high five')
我收到错误,所以我尝试了:
d.add_trick(['play dead', 'high five'])
但这给了我:
d.tricks
['roll over', 'fetch', ['play dead', 'high five']]
我想要的时候:
['roll over', 'fetch', 'play dead', 'high five']
如何取消添加到课程中的项目列表?
答案 0 :(得分:0)
使用extend
:
d.tricks.extend(['play dead', 'high five'])
d.tricks
['roll over', 'fetch', 'play dead', 'high five']
或者您可以将add_tricks
更改为:
def add_trick(self, *trick):
self.tricks.extend(trick)
答案 1 :(得分:0)
您可以重新定义Dog.add_trick
方法以获取可变数量的参数,然后使用list.extend
将它们全部添加到列表中:
def add_trick(self, *tricks):
self.tricks.extend(tricks)
演示:
>>> class Dog:
... def __init__(self, name):
... self.name = name
... self.tricks = []
... def add_trick(self, *tricks):
... self.tricks.extend(tricks)
...
>>> d = Dog('Fido')
>>> d.add_trick('roll over')
>>> d.add_trick('fetch')
>>> d.tricks
['roll over', 'fetch']
>>> d.add_trick('play dead', 'high five')
>>> d.tricks
['roll over', 'fetch', 'play dead', 'high five']
>>>
有关*tricks
语法的更多信息,请参阅文档中的Function definitions。