对象位置是对象的打印方式。严格地说,在list上调用str或repr会对列表中的每个元素调用repr。默认情况下,Teams对象上的repr(team)将返回类似的内容。您可以通过在Teams类上定义repr方法来覆盖它。但是,这听起来不像你想要的。
如果TeamList是Teams对象的列表,并且您想将其转换为其TeamName成员的列表,则只需使用list comprehension进行转换:
TeamNameList = [team.TeamName for team in TeamList]请注意,这仍然不是您想要打印出来的:
>>> print TeamNameList
['North Carolina', 'South Carolina', 'West Carolina', 'East Carolina', 'Underground Carolina', 'Cloud-level Carolina', 'Past Carolina', 'Future Carolina'] # those are all states, right?你可能想要这样的东西:
>>> print ', '.join(TeamNameList)
North Carolina, South Carolina, West Carolina, East Carolina, Underground Carolina, Cloud-level Carolina, Past Carolina, Future Carolina从你的评论:
there is a later function simGame(teamA, Teamb)
I see the instances, however I am not sure how to call them in the second function. I had planned on calling them by name. In the example I gave, North_carolina can be passed to the later (not shown function) and calculations can be run on the data
我想我明白你想要的东西。您希望能够模拟北卡罗来纳州和南卡罗来纳州之间的游戏,当您拥有的只是TeamList时。
为此,您可能想要创建一个dict,将名称映射到Teams对象,如下所示:
TeamDict = {team.TeamName: team for team in TeamList}现在,你可以这样做:
simGame(TeamDict['North Carolina'], TeamDict['South Carolina'])现在,simGame将把Teams类的北卡罗来纳州和南卡罗来纳州实例作为其teamA和teamB参数,因此它可以执行以下操作:
def simGame(teamA, teamB):
scoreA = int(teamA.FT * 1 * 20) + int(teamA.FG * 2 * 40) + int(teamA.Three * 3 * 10)
scoreB = int(teamB.FT * 1 * 20) + int(teamB.FG * 2 * 40) + int(teamB.Three * 3 * 10)
if scoreA > scoreB:
print 'Home team {} beats visitor {} by {}!'.format(teamA.TeamName,
teamB.TeamName,
scoreA - scoreB)
else:
print 'Visitors {} win by {} over {} at home!'.format(teamB.TeamName,
scoreB - scoreA,
teamA.TeamName)那是你要的吗?
一些额外的评论:
您也可以使用map执行与列表推导相同的操作,这样可以避免必须两次写入team,但这也意味着您无法使用普通表达式语法:
TeamNameList = map(operator.attrgetter('TeamName'), TeamList)或者您可以将map与lambda一起使用以取回表达式语法...并重复team:
TeamNameList = map(lambda team: team.teamName, TeamList)但对于这样的情况,列表理解通常被认为是做到它的pythonic方式。 (另外,如果你去Python 3,它不会改变,而map从list变为迭代器,这意味着print TeamNameList会给你类似 ......但是', '.join(TeamNameList)仍然可以工作。)
作为旁注,在标准(PEP 8)Python样式中,通常只有这样的类在TitleCase中,变量和属性在lower_case中。如果您真的喜欢CamelCase,那么您可以使用lowerFirstCamelCase,但使用TitleCase会让人们阅读您的代码,他们将立即尝试找出TeamName类的定义位置。另见bvukelic的评论。
另外一点,你似乎做了很多重复的代码,我不知道为什么:
name = info[0]
FT = info[1]
FG = info[2]
Three = info[3]
newTeam = (name, FT, FG, Three)您只是将info复制到newTeam;为什么要添加所有那些永远不会再次使用的中间变量?
newTeam2 = Teams(newTeam[0],newTeam[1],newTeam[2],newTeam[3])你可以用以下方式替换所有这些:
newTeam2 = Teams(info[0],info[1],newTeam[2],newTeam[3])甚至:
newTeam2 = Teams(*info)如果你需要在某个你没有向我们展示的单独变量,那很好,但是你仍然不可能需要newTeam;这样做:
newTeam2 = Teams(name, FT, FG, Three)