Python格式打印以均匀打印数字

时间:2014-12-06 23:21:41

标签: python python-3.x format

我有一个整数数组,我试图均匀地打印出来,比如说数据集是

7 14 23 49 191

我使用

循环遍历此数组content
for num in content:
    print(num,"",end="")

现在我需要在列表中的某些元素上方放置|(通过控制台生成方框图)。当某些整数占用额外空间时,如何知道|符号的放置位置?我试过了

#print | above certain numbers
for num in content:
    if num == theone:
        print("|",end="")
    else:
        print(" ",end="")

#print numbers as before
for num in content:
    print(num,"",end="")

但这会给我

  |  | 
7 14 23 49 191

而不是

   |     |
7 14 23 49 191

因为下面的整数不只是一位数。有没有简单的方法来解决这个问题?感谢

4 个答案:

答案 0 :(得分:3)

尝试这样的事情:

content = [7, 14, 23, 49, 191,]
ticks = [0,1,0,1,0]

fmt = '{:>5}'

for tic in ticks:
    print(fmt.format('|' if tic else""), end="")
print()
for num in content:
    print(fmt.format(num) ,end="")
print()

编辑:根据Ashwini Chaudhary的评论,要产生确切的格式,请尝试以下方式:

content = [7, 14, 23, 49, 191]
widths = [' '*len(str(c)) for c in content]
the_ones = [False, True, False, True, False] # or any other way to
                                             # signal which ones to tick
for i, t in enumerate(the_ones):
    if t == True:
        widths[i] = widths[i][:-1]+'|'

print(' '.join(widths))
print(' '.join(map(str, content)))

答案 1 :(得分:1)

您可以这样做:

lst = [7, 14, 23, 49, 191]

for x in lst:
    n = len(str(x))
    if x in (14, 49): #some condition
        # if we want to print the | at the end of the number then we first need
        # to add (n-1) spaces before it and then add a |. Lastly end with a ' '
        # so that the cursor moves to the start of next number.
        print (' ' * (n-1) + '|', end=' ')
    else:
        # simply print n space so that cursor moves to the end of the number
        # and end it with a ' ' to move the cursor to the start of next number
        print (' ' * n, end=' ')

print()

for x in lst:
    print (x, end=' ')

<强>输出:

   |     |     
7 14 23 49 191 

答案 2 :(得分:0)

您可以使用数字的固定宽度表示:

# Sample data
content = [1, 10, 100, 1000]

# Will be 4, since 1000 has four digits
max_digits = max(len(str(n)) for n in content)

# '<4' will be left-aligned; switch to > for right-aligned
fmt_string = '<{}'.format(max_digits)

# Print out the digits
for n in content:
    s = format(n, fmt_string)
    # Do your thing to determine whether to place a bar
    print(s, end='')

有关字符串格式的信息,请参阅more

答案 3 :(得分:0)

from math import floor,ceil
numbers = [7, 14, 23, 49, 191]
selection = [14, 49]
indexes = sorted([numbers.index(n) for n in selection])

def selectors():
    string = ""
    for n in xrange(len(numbers)):
        len_number = len(str(numbers[n]))
        if len_number == 1:
            pad = "|"
        elif len_number == 2:
            pad = " |"
        else:
            pad = " " * (int(ceil(len_number / 2.0)-1)) + "|" + " " * (int(floor(len_number / 2.0)))
        if n not in indexes:
            pad = pad.replace("|", " ")
        string += pad+" "
    return string

print (selectors())
print (" ".join([str(n) for n in numbers]))

输出:

   |     |     
7 14 23 49 191

实际上这个很简单,

它会将管道(&#34; |&#34;)添加到字符串中的每个字符,正好在中间,如果数字不在选择中,则用空格替换管道字符。

其他例子

numbers = [0,100,1000,10000,100000, 1000000, 10000000]
selection = [1000, 100000, 10000000]

       |           |               |     
0 100 1000 10000 100000 1000000 10000000