简体   繁体   中英

How to format lists in a vertical and horizontal way in Python 3x?

I'm trying to develop a new encrypting system. I want to horizontally and vertically format a list. for education for example

l1=[A,B,C,£,D,E,F,£,G,H,I...,£,W,X,Y,Z]#(continues like phone keyboard)

I want it to make a new column when it sees "£" Some of the columns contain 4 letters I want to format it like:

A D G     W
B E H ... X
C F I     Y
          Z

It will do this later: İf we want it to write "OMG":

M M G       . * *
N N H ----> . . .
O O I       * . .

To format the lists, you can use itertools.zip_longest :

import itertools
l1=['A','B','C']
l2=['D','E','F','G']
new_l = '\n'.join(' '.join(i) for i in itertools.zip_longest(l1, l2, fillvalue=' '))
print(new_l)

Output:

A D
B E
C F
  G

Edit: you can use itertools.groupby :

import itertools
l1=['A','B','C','£','D','E','F','£','G','H','I','£','W','X','Y','Z']
new_l = zip(*[list(b) for a, b in itertools.groupby(l1, key=lambda x:x != '£') if a])
final_l = '\n'.join(' '.join(b) for b in new_l)

Output:

A D G W
B E H X
C F I Y
import itertools
l1=['A','B','C'] 
l2=['D','E','F','G'] 

for first, last in list(itertools.zip_longest(l1, l2, fillvalue=' ')): 
    print(first, last)

output

A D
B E
C F
  G

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM