Pythonの2次元配列を1次元配列に変換する4つの方法
11591 ワード
2 D配列を1 D配列に変換
a=[[4,0,1],[9,2,7],[8,12,90]]が知られている.
リスト導出式
itertools
sumテクニック
operator
実戦(スパイラルマトリクス)
a=[[4,0,1],[9,2,7],[8,12,90]]が知られている.
リスト導出式
[i for j in a for i in j]
itertools
from itertools import chain
list(chain.from_iterable(a))
sumテクニック
sum(a, [])
operator
import operator
from functools import reduce
print(reduce(operator.add, a))
実戦(スパイラルマトリクス)
def fun(arr, lines):
total_matrix = [[0] * lines for i in range(lines)]
""" """
num = [i for j in arr for i in j]
num = sorted(num)
show_num = 0
col = lines - 1
row = lines - 1
start_line = 0
def print_ju(start_line, col, row, show_num):
if row == 0:
if lines % 2 != 0:
total_matrix[lines // 2][lines // 2] = lines * lines
else:
for i in range(start_line, col): #
total_matrix[start_line][i] = num[show_num]
show_num += 1
for i in range(start_line, row, 1): #
total_matrix[i][col] = num[show_num]
show_num += 1
for i in range(row, row - col + start_line, -1): #
total_matrix[row][i] = num[show_num]
show_num += 1
for i in range(col, col - row + start_line, -1): #
total_matrix[i][row - col + start_line] = num[show_num]
show_num += 1
return print_ju(start_line + 1, row - 1, col - 1, show_num)
print_ju(start_line, row, col, show_num)
for i in total_matrix:
for x in i:
print(format(x, '3'), end=' ')
print()
if __name__ == '__main__':
n = int(input(' :'))
arr = [[4, 0, 1], [9, 2, 7], [8, 12, 90]]
fun(arr, n)