简体   繁体   中英

Python Two-Dimensional Array

在此处输入图像描述

Hello. There is a key that is written vertically in 1 column “HELLO.” It is necessary to fill the letters vertically alphabetically as in the table.

The matrix should be square ( same number of rows than columns ). Can you help please. I placed the key vertically, but I cannot horizontally write the letters of the alphabet.

key='HELLO'
f=[]
count = 1
A = [['' for i in key] for i in key]
for i in range(len(A)):
    A[i][0]=key[i]
for i in range(0,len(A)):
  for j in range(0,len(A[i])):
      if A[i][0]==key[i]:
            n=count+ord(key[i])
            A[j][i]=n

The following code

from itertools import cycle 
from string import ascii_uppercase 
letter = cycle(ascii_uppercase)

column1 = 'HELLO'
len_other_columns = len(column1)-1
other_columns = range(len_other_columns)

for letter1 in column1: 
    while next(letter) != letter1: ... 
    print(letter1, ' '.join(next(letter) for _ in other_columns))

produces

H I J K L
E F G H I
L M N O P
L M N O P
O P Q R S

To place the result in a list of lists, or 2D array,

from itertools import cycle 
from string import ascii_uppercase 
letter = cycle(ascii_uppercase)

column1 = 'HELLO'
len_other_columns = len(column1)-1
other_columns = range(len_other_columns)
# Initialize the 2D array
two_d_array = [[c] for c in column1]
# similar to the previous
for sublist in two_d_array:
    while next(letter) != sl[0]: ...
    for _ in other_columns: sublist.append(next(letter))
print(two_d_array)

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