简体   繁体   English

Python列表 - 行和列

[英]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; 基本上我的目标是这样 - 以无限数量的行打印列表(所以基本上消息可以是行中的任何长度),但是将列数限制为4.所以我希望示例看起来更像这样;

    ['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. 所以重申一下,取决于编码消息的长度取决于行数,但是我想将列数限制为4,我不确定如何执行此操作。

Many thanks. 非常感谢。

You can flatten the list with itertools: 您可以使用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. 这里似乎你有一个复制粘贴错误,因为你只需要在切片时将6更改为4 Also note that you use two different lists for the range and for the slice. 另请注意,您为range和切片使用两个不同的列表。 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: 或者没有itertools或其他模块:

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. Numpy应该能够很容易地处理这个问题。 If codedmessage is a list: 如果codedmessage是一个列表:

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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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