python 如何将2d列表打印为偶数表?

but5z9lq  于 2023-01-04  发布在  Python
关注(0)|答案(2)|浏览(86)
#Create a program that allows 2 players to throw a 6 sided dice and record the roll value 10 times. 
#The winner is the player with the highest total 
#This task must store the results in a 2D array 

#Extra: 
#Work out the average roll across the 10 throws per player and display the result 
#Frequency analysis broken down per player and per game

from random import randint

results = [[],[]]

for i in range (2):
    
    player = []
    total = 0
    average = 0
    
    #player enters their name
    name = input(f"\nEnter your name player {i + 1}: ")
    player.append(name)
    
    print(f"Player {i + 1} it is your turn")
    
    for x in range(10):
        print("\nTo roll the die press any key")
        input()
    
        roll = randint(1,6)
        player.append(roll)
        print("You rolled a", roll)
        total += roll
    
    average = total/10
    
    player.append(total)
    player.append(average)
    results.append(player)
    
print("""\nNAME  R1  R2  R3  R4  R5  R6  R7  R8  R9  R10  TOTAL  AVG""")

for i in results:
    for c in i:
        print(c,end = "   ")
    print()

我不知道如何均匀地间隔这些值,以便在打印时它们保持一致。
我试着在打印时在值之间添加空格,但如果其中一个名称或数字的长度不同,则整行与列不对齐。

sq1bmfud

sq1bmfud1#

可以使用以下语法:

print('%5s' % str(c))

基本上:

  • %字符通知python它必须替换某个令牌
  • s字符通知python标记将是字符串
  • 5(或者任何你想要的数字)通知python用空格填充字符串,最多5个字符。

我在How to print a string at a fixed width?上找到的。

7cjasjjr

7cjasjjr2#

计算两个名称之间的差异

diff = abs(len(results[2][0]) - len(results[3][0])) #abs = absolute value

比较名称的2个长度:

if len(results[2][0] ) > len(results[3][0]):
    results[3][0] = results[3][0] + " "*diff # add spaces much as difference between 2 names
else:
    results[2][0] = results[2][0] + " "*diff

相关问题