如何将用户输入的 8 个数字列表分成四等分

问题描述

目前,我有 data = input('Please input 8 numbers \n') 我想要做的是将这个列表分成四部分,这样我就可以将它们输入到 2x2 格式的矩阵 A 和 B 中

解决方法

是的,为此,你可以做到

data = input('Please input 8 numbers \n')
quarters = []
split_input = data.split(" ")
for i in range(0,len(split_input),2):
    quarters.append([split_input[i],split_input[i+1]])

print(quarters)
Please input 8 numbers 
1 2 3 4 5 6 7 8
[['1','2'],['3','4'],['5','6'],['7','8']]
,

取决于输入应存储在 A、B 中的顺序:

import numpy as np

split_input = input('Please input 8 numbers \n').split(" ")
A,B = np.array(split_input,dtype='float').reshape(2,2,2)

print(A)
print(B)
Please input 8 numbers 
1 2 3 4 5 6 7 8
[[1. 2.]
 [3. 4.]]
[[5. 6.]
 [7. 8.]]

arr = np.array(split_input,2)
A,B = np.swapaxes(arr,1)

print(A)
print(B)
[[1. 2.]
 [5. 6.]]
[[3. 4.]
 [7. 8.]]

arr = np.array(split_input,1,2)

print(A)
print(B)
[[1. 3.]
 [2. 4.]]
[[5. 7.]
 [6. 8.]]

,

分隔
import numpy as np

_input = input('Please input 8 numbers \n')
int_input = [int(x) for x in _input.split(',')]
x = np.array(int_input).reshape(2,2)