Python列表对齐
我有一项任务要完成 我有100个随机整数。从这100个我必须创建一个10x10表。完成。。 在该表中,我必须将我的值和每列的右侧对齐。这是我错过的部分 以下是代码:Python列表对齐,python,for-loop,Python,For Loop,我有一项任务要完成 我有100个随机整数。从这100个我必须创建一个10x10表。完成。。 在该表中,我必须将我的值和每列的右侧对齐。这是我错过的部分 以下是代码: print(num, end=(" " if counter < 10 else "\n")) print(num,end=(“if counter5}”,end=(“”如果计数器
print(num, end=(" " if counter < 10 else "\n"))
print(num,end=(“if counter<10 else”\n))
您可以在打印之前格式化数字
print(f"{num:>5}", end=(" " if counter < 10 else "\n"))
print(f“{num:>5}”,end=(“”如果计数器<10 else“\n”))
或者,如果你想把数字转换成字符串,你可以使用rjust的string方法。有一个简单的方法。我希望我已经讲清楚了
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)
输出为:
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
延迟回答,但您也可以使用:
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 " "))
每个人都知道95%的代码需要95%的精力/时间。最后的5%又花费了95%的精力/时间:-)您需要搜索的是
fstrings
(首选)或格式
字符串方法。
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