如何在这个线程中创建漂亮的列

时间:2014-06-12 19:51:52

标签: python

我在python中编写了一个脚本,最后我得到了这样的结果:

urls = open(filename)
for line in urls:
    url = line.rstrip()
    data = Func(url)
    if data:
        line, a_param, b_param, c_param = data
        print '%s %d %d %d' % (line, a_param, b_param, c_param)

所以我想为输出做一个很好的专栏......你能帮助我吗?

我尝试的是:

out = '%s %d %d %d' % (line, a_param, b_param, c_param)
        col_width = max(len(word) for row in out for word in row) + 2 
        for row in out:
            print "%s %d %d %d".join(word.ljust(col_width) for word in row)

但没有结果......我的意思是输出结果:

t
e
s
t

1  
9  
8  
4  
7  
9  
0  
0  

2  
0  
0  
7  
7  
5  
9  
0  

-  
1 

我也改变了代码:

for row in out:
            print('{0:s} {1:d} {2:d} {3:d}'.format(str(row), int(row), int(row), int(row)))

发生了以下错误:

ValueError: invalid literal for int() with base 10: 'l'

3 个答案:

答案 0 :(得分:1)

如果这些是具有不同位数的整数,您可以告诉print使用固定大小的列,例如像这样:

>>> for i in [-1, 40, 999, 2]:
...   print "[% 5d]" % i
... 
[   -1]
[   40]
[  999]
[    2]

所以,如果您知道列的最大长度,您可以在格式字符串中明确指定它:

print '% 10s % 5d % 4d % 3d' % ...

此处概述了不同的格式选项:https://docs.python.org/2/library/stdtypes.html#string-formatting

答案 1 :(得分:0)

将所有参数的字符串转换为列表:

words = out.split()

然后计算最长的"字"

col_width = max(len(word) for word in words) + 2

并在cols中设置

for word in words:
    print("".join(word.ljust(col_width)), end="")

这有帮助吗?

答案 2 :(得分:0)

我认为问题在于你是以错误的方式进行迭代。你分配给一个str,然后迭代str。您想迭代在数据中找到的项目。

out = []
maxlen = 0
urls = open(filename)
for line in urls:
    url = line.rstrip()
    data = Func(url)
    if data:
        # calculate the longest word.
        tmplen = max(len(word) for word in data)
        # store the result
        maxlen = tmplen if templen > maxlen else maxlen
        # keep the data around for iterating later
        out.append(data)

# loop through all of the data stored earlier 
for line in out:
    # lambda creates a function.
    # str(x) converts to a str, ljust makes it the right length
    # map applies the function to all of the items in the list.
    print ''.join(map(lamda x: str(x).ljust(maxlen), line))