首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将2d列表打印为偶数表?

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

Stack Overflow用户
提问于 2022-11-26 12:50:26
回答 2查看 35关注 0票数 1
代码语言:javascript
运行
复制
#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()

我不知道如何将这些值均匀地划出,以便它们在打印时是一致的。

打印时,我尝试在值之间添加空格,但如果其中一个名称或数字的长度不同,则整个行将与该列不对齐。

EN

回答 2

Stack Overflow用户

发布于 2022-11-26 13:18:39

您可以使用以下新税:

代码语言:javascript
运行
复制
print('%5s' % str(c))

基本上:

  • %字符通知python它将不得不替换一个令牌
  • s字符通知python令牌将是字符串
  • 5 (或任意数字)通知python填充最多5个字符的字符串。H 210f 211

我在How to print a string at a fixed width?上发现的。

票数 1
EN

Stack Overflow用户

发布于 2022-11-26 12:56:09

计算两个名称之间的差额

代码语言:javascript
运行
复制
diff = abs(len(results[2][0]) - len(results[3][0])) #abs = absolute value

比较两个名字的长度:

代码语言:javascript
运行
复制
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
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74582309

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档