首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python列表对齐

Python列表对齐
EN

Stack Overflow用户
提问于 2021-03-11 20:56:47
回答 3查看 153关注 0票数 1

我要完成一项任务。

我有100个随机整数。从这100中,我必须创建一个10x10表。完成了..。在该表中,我必须将我的值与每列的右侧对齐。这是我错过的部分。

以下是这方面的代码:

代码语言:javascript
复制
    print(num, end=("  " if counter < 10 else "\n"))
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2021-03-11 21:03:26

您可以先格式化数字,然后再打印它。

代码语言:javascript
复制
print(f"{num:>5}", end=("  " if counter < 10 else "\n"))

或者,如果要将数字转换为string,则可以使用string的rjust方法。

票数 0
EN

Stack Overflow用户

发布于 2021-03-11 22:01:29

迟答,但您也可以使用:

代码语言:javascript
复制
import random

rl = random.sample(range(100, 999), 100)
max_n = 10
for n, x in enumerate(rl, 1):
  print(x, end=("\n" if n % max_n == 0 else "  "))

代码语言:javascript
复制
440  688  758  837  279  736  510  706  392  631
588  511  610  792  535  526  335  842  247  124
552  329  245  689  832  407  919  302  592  385
542  890  406  898  189  116  495  764  664  471
851  728  292  314  839  503  691  355  350  213
661  489  800  649  521  958  123  205  983  219
321  633  120  388  632  187  158  576  294  835
673  470  699  908  456  270  220  878  376  884
816  525  147  104  602  637  249  763  494  127
981  524  262  915  267  873  886  397  922  932
票数 1
EN

Stack Overflow用户

发布于 2021-03-11 21:11:25

有一种简单的方法。我希望我已经说清楚了。

代码语言:javascript
复制
import random
# Generate 100 random numbers in range 1 to 1000.
random_numbers = list(map(lambda x:random.randrange(1,1000), range(100)))
# Create an empty string to store the pretty string.
pretty_txt = ''

# Loop through random_numbers and use an enumerate to get iteration count.
for index, i in enumerate(random_numbers):
    # Add the current number into the string with a space.
    pretty_txt += str(i) + ' '
    # Add a newline every ten numbers. 
    # If you don't add index != 0 it will put a space in first iteration
    if index % 9 == 0 and index != 0:
        pretty_txt += '\n'

print(pretty_txt)

产出如下:

代码语言:javascript
复制
796 477 578 458 284 287 43 535 514 504 
91 411 288 980 85 233 394 313 263 
135 770 793 394 362 433 370 725 472 
981 932 398 275 626 631 817 82 551 
775 211 755 202 81 750 695 402 809 
477 925 347 31 313 514 363 115 144 
341 684 662 522 236 219 142 114 621 
940 241 110 851 997 699 685 434 813 
983 710 124 443 569 613 456 232 80 
927 445 179 49 871 821 428 750 792 
527 799 878 731 221 780 16 779 333 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66590447

复制
相关文章

相似问题

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