从列表和嵌套列表打印到表格形式

问题描述 投票:0回答:2

pset这是到目前为止我的代码:

MEDALS = 3
COUNTRIES = 8
# Create a list of country names.
countries = [ "Canada", "Italy", "Germany", "Japan",
            "Kazakhstan", "China",
            "South Korea", "United States" ]
# Create a table of medal counts.
counts = [
            [ 0, 3, 0 ],
            [ 0, 0, 1 ],
            [ 0, 0, 1 ],
            [ 1, 0, 0 ],
            [ 0, 0, 1 ],
            [ 3, 1, 1 ],
            [ 0, 1, 0 ],
            [ 1, 0, 1 ]
        ]

print('       Country  Gold  Silver  Bronze  Total')
for v in countries:
    country = v
    print("{:>13}".format(country))
for row in range(COUNTRIES):
    for col in range(MEDALS):
        print(counts[row][col],end = ' ')
    print('')

应该在不使用任何导入模块的情况下解决这个问题。我该如何做到这一点,请向我解释一下?非常感谢你。

我可以将数字打印在表格下方,但不能像应有的那样打印在表格的列中。

python dictionary for-loop iteration
2个回答
0
投票

您的代码现在显示:打印所有国家/地区

for v in countries:
,然后打印所有奖牌
for row in range(COUNTRIES)
,要打印表格,您需要将第二个循环嵌套在第一个循环中。


0
投票

因此,这里的主要技巧是将相应国家/地区的奖牌数量加入其中,并将其作为一个整体进行迭代。

for country_name, medal_counts in zip(countries, counts):
    gold, silver, bronze = medal_counts
    total = sum(medal_counts)
    print(country_name, gold, silver, bronze, total)

一旦你做到了这一点,你或多或少就已经有了完整的答案,只需要使用一个好的格式模板即可。请注意,有很多方法可以获得与

zip()
相同的结果。

例如:

for index in range(len(countries)):
    country_name = countries[index]
    medal_counts = counts[index]

    gold, silver, bronze = medal_counts
    total = sum(medal_counts)
    print(country_name, gold, silver, bronze, total)

zip()
只为您做。

为了完善它,让我们使用您开始使用的格式模板。

# Create a list of country names.
countries = [
    "Canada",
    "Italy",
    "Germany",
    "Japan",
    "Kazakhstan",
    "China",
    "South Korea",
    "United States"
]

# Create a table of medal counts.
counts = [
    [ 0, 3, 0 ],
    [ 0, 0, 1 ],
    [ 0, 0, 1 ],
    [ 1, 0, 0 ],
    [ 0, 0, 1 ],
    [ 3, 1, 1 ],
    [ 0, 1, 0 ],
    [ 1, 0, 1 ]
]

## -----------------
## Now we just need to make it look nice
## -----------------
template = "{country_name:>15} {gold:>8} {silver:>8} {bronze:>8} {total:>8} "

print(template.format(country_name="", gold="Gold", silver="Silver", bronze="Bronze", total="Total"))
for country_name, medal_counts in zip(countries, counts):
    gold, silver, bronze = medal_counts
    total = sum(medal_counts)
    print(template.format(country_name=country_name, gold=gold, silver=silver, bronze=bronze, total=total))
## -----------------

这会给你:

                    Gold   Silver   Bronze    Total
         Canada        0        3        0        3
          Italy        0        0        1        1
        Germany        0        0        1        1
          Japan        1        0        0        1
     Kazakhstan        0        0        1        1
          China        3        1        1        5
    South Korea        0        1        0        1
  United States        1        0        1        2
© www.soinside.com 2019 - 2024. All rights reserved.