Python中的二维列表?

时间:2012-03-27 05:55:17

标签: python list

所以我有这段代码:

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]

我想制作一对二维队伍之间的分数差异列表。 输出可以是这样的: Output

最简单的方法是什么?谢谢:))

5 个答案:

答案 0 :(得分:6)

你可以尝试:

[[x[1]-y[1] for y in TeamList] for x in TeamList]

这将生成一个表示建议输出的嵌套列表(当然没有列和行标题)。

答案 1 :(得分:4)

只使用制表符而不是任何花哨的格式来构建图表:

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

答案 2 :(得分:3)

您可以尝试嵌套for循环。这样的事情: -

for team1 in TeamList:
    for team2 in TeamList:
        print team1[1]-team2[1]

这将给出得分差异。必须对输出进行格式化以获得您想要的精确表格。

答案 3 :(得分:3)

列表理解可行(但嵌套列表推导并不适合我。)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.

答案 4 :(得分:0)

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)))