开发者

Printing list with set width in python

开发者 https://www.devze.com 2023-04-03 22:33 出处:网络
qu开发者_JAVA技巧ick and hopefully easy question. Let\'s say I have a variable that is equal to a numerical width value

qu开发者_JAVA技巧ick and hopefully easy question.

Let's say I have a variable that is equal to a numerical width value

i.e.: size_x = 50

I want to print the list, wrapping to a width of 50 elements. How do I do this?


guess 1: print lines containing only size_x elements of the original list

for i in range(len(mylist)/size_x):
    print(mylist[i*size_x:(i+1)*size_x])

guess 2: a new list of which the elements are strings of only size_x characters

newlist = []
for i in range(len(mylist)/size_x):
    newlist.append(''.join(mylist[i*size_x:(i+1)*size_x]))

printing newlist of 'guess 2' all at once to the screen is quicker than first guess:

print('\n'.join(newlist))

(also note that prior to python 3, xrange() can be used instead of range(), which generates i-values 'on the go' instead of creating a whole list of indices first. Python 3 does this standard with range())

example

mylist = list('hello this is supposed to be a long line')
size_x=5
for i in range(len(mylist)/size_x):
    print(mylist[i*size_x:(i+1)*size_x])

['h', 'e', 'l', 'l', 'o']
[' ', 't', 'h', 'i', 's']
[' ', 'i', 's', ' ', 's']
['u', 'p', 'p', 'o', 's']
['e', 'd', ' ', 't', 'o']
[' ', 'b', 'e', ' ', 'a']
[' ', 'l', 'o', 'n', 'g']
[' ', 'l', 'i', 'n', 'e']

newlist = []
for i in range(len(mylist)/size_x):
    newlist.append(''.join(mylist[i*size_x:(i+1)*size_x]))
print('\n'.join(newlist))

hello
 this
 is s
uppos
ed to
 be a
 long
 line
0

精彩评论

暂无评论...
验证码 换一张
取 消