我必须使用类和继承从列表中获取项目,并将它们随机平均地附加到两个列表中,所以我不知道如何将它们随机添加到列表中
import random
players = ['a', 'b', 'c','d','e', 'f']
A = []
B = []
teams = []
class Human:
def __init__(self,name):
self.name = name
class Player(Human):
def __init__(self, name, team):
self.team = team
Human.__init__(self, name)
for i in range(6):
p = Player(random.choice(players))
a = p.team
print(p.name)
players.remove(p.name)
print(teams)
答案 0 :(得分:5)
您的代码将为您提供相同的玩家:
for i in range(6): p = Player(random.choice(players)) # you can draw duplicates here
避免在您的全名上使用random.sample(players, k=len(players))
(这将返回一个新的,经过改组的列表-players
未修改)或就地使用random.shuffle(players)
。然后,将结果分为两部分,并根据该数据创建团队:
您可能应该重载类的__repr__(self)
方法,以使输出更整洁。
import random
class Human:
def __init__(self,name):
self.name = name
def __str__(self):
return f"{self.name}"
def __repr__(self): return str(self)
class Player(Human):
def __init__(self, name, team):
super().__init__(name)
self.team = team
def __str__(self):
return f"{self.name} in team {self.team}"
def __repr__(self): return str(self)
players = ['a', 'b', 'c','d','e', 'f']
random.shuffle(players) # inplace shuffling
player_length = len(players) // 2 # make sure you got even player counts - else uneven teams
A = [Player(k,"A") for k in players[:player_length]] # first 3 are Team A
B = [Player(k,"B") for k in players[player_length:]] # rest is Team B
teams = [A,B]
print(teams)
输出:
[[d in team A, f in team A, b in team A],[a in team B, e in team B, c in team B]]
Doku: