简体   繁体   中英

Python List - rows and columns

I have the following code;

for d in range(0,len(newlist),4):
    codewordgrid.append(list(codedmessage[d:d+6]))

This then prints something along the lines of this;

<<<CODEWORD GRID>>>
[['E', 'A'], ['E', 'A'], ['E', 'A'], ['F', 'C'], ['F', 'C'], ['F', 'C']]
[['F', 'C'], ['F', 'C'], ['F', 'A'], ['F', 'A'], ['F', 'A'], ['C', 'A']]
[['F', 'A'], ['C', 'A'], ['C', 'A'], ['C', 'A']]
[]
[]
[]
[]
[]
[]

Basically my aim is this - to print the list in an unlimited number of rows (so basically the message can be any length in rows), but to limit the number of columns to 4. So I would like the example to look more like this;

    ['E', 'A'], ['E', 'A'], ['E', 'A'], ['F', 'C']
    ['F', 'C'], ['F', 'C'], ['F', 'C'], ['F', 'C']
    ['F', 'A'], ['F', 'A'], ['F', 'A'], ['C', 'A']
    ['F', 'A'], ['C', 'A'], ['C', 'A'], ['C', 'A']

So just to reiterate, depending on how long the codedmessage is depends on the amount of rows, however I would like to limit the number of columns to 4 and I am unsure how to do this.

Many thanks.

You can flatten the list with itertools:

chain = itertools.chain.from_iterable(your_nested_list):
for i in range(0, len(chain), 4):
   print str(chain[i:i+4])[1:-1]

It seems you have a copy-paste error here, as you just have to change the 6 to 4 when you do the slice. Also note that you use two different lists for the range and for the slice. I think you meant this:

for d in range(0,len(codedmessage),4):
    codewordgrid.append(list(codedmessage[d:d+4]))

Or without itertools or other modules:

def eachToken(codewordgrid):
  for element in codewordgrid:
    for token in element:
      yield token

for i, token in enumerate(eachToken(codewordgrid)):
  print token, ("," if i % 4 else "\n"),
print

Numpy should be able to handle this pretty easily. If codedmessage is a list:

import numpy
codewordgrid = numpy.array(codedmessage).reshape(-1,4,2)
numpy.savetxt('codewordgrid.txt',codewordgrid,fmt='%s',delimiter=", ")

The only difference here is that there won't be a comma between codeword pairs.

eg

['E' 'A'], ['E' 'A'], ['E' 'A'], ['F' 'C']
['F' 'C'], ['F' 'C'], ['F' 'C'], ['F' 'C']
['F' 'A'], ['F' 'A'], ['F' 'A'], ['C' 'A']
['F' 'A'], ['C' 'A'], ['C' 'A'], ['C' 'A']

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