[英]Two-dimensional list in Python?
所以我有这个代码:
Team1 = ["Red", 10]
Team2 = ["Green", 5]
Team3 = ["Blue", 6]
Team4 = ["Yellow", 8]
Team5 = ["Purple", 9]
Team6 = ["Brown", 4]
TeamList = [Team1, Team2, Team3, Team4, Team5, Team6]
我想制作一组两队之间得分差异的二维列表。 输出可以是这样的:
最简单的方法是什么? 谢谢 :)
你可以尝试:
[[x[1]-y[1] for y in TeamList] for x in TeamList]
这将生成一个表示建议输出的嵌套列表(当然没有列和行标题)。
只使用制表符而不是任何花哨的格式来构建图表:
Team1 = ["Red", 10]
Team2 = ["Green", 5]
Team3 = ["Blue", 6]
Team4 = ["Yellow", 8]
Team5 = ["Purple", 9]
Team6 = ["Brown", 4]
TeamList = [Team1, Team2, Team3, Team4, Team5, Team6]
# print the top row of team names, tab separated, starting two tabs over:
print '\t\t', '\t'.join(team[0] for team in TeamList)
# for each row in the chart
for team in TeamList:
# put two tabs between each score difference column
scoreline = '\t\t'.join(str(team[1] - other[1]) for other in TeamList)
# and print the team name, a tab, then the score columns
print team[0], '\t', scoreline
您可以尝试嵌套for循环。 像这样: -
for team1 in TeamList:
for team2 in TeamList:
print team1[1]-team2[1]
这将给出分数差异。 必须格式化输出以获得所需的精确表格外观。
列表理解可行(但嵌套列表itertools.product()
并不适合我。) itertools.product()
是另一种方式。
考虑以下因素:
import itertools
scores = {
"Red" : 10,
"Green" : 5,
"Blue" : 6,
"Yellow": 8,
"Purple": 9,
"Brown" : 4,
}
for team_1, team_2 in itertools.product(scores, scores):
print ("Team 1 [%s] scored %i, Team 2 [%s] scored %i." % (team_1, scores[team_1], team_2, scores[team_2]) )
哪个输出:
Team 1 [Blue] scored 6, Team 2 [Blue] scored 6.
Team 1 [Blue] scored 6, Team 2 [Brown] scored 4.
... (32 more lines) ...
Team 1 [Red] scored 10, Team 2 [Green] scored 5.
Team 1 [Red] scored 10, Team 2 [Red] scored 10.
Team1 = ["Red", 10]
Team2 = ["Green", 5]
Team3 = ["Blue", 6]
Team4 = ["Yellow", 8]
Team5 = ["Purple", 9]
Team6 = ["Brown", 4]
TeamList = [Team1, Team2, Team3, Team4, Team5, Team6]
# calculate scores
scores = [[x[1]-y[1] for y in TeamList] for x in TeamList]
# print the top row of team names, tab separated, starting two tabs over:
print('\t\t', '\t'.join(team[0] for team in TeamList))
# for each row in the chart
for score, team in zip(scores,TeamList):
print(("%s"+"\t%s"*len(TeamList)) % ((team[0],)+tuple(score)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.