我正在阅读来自CSV
文件的数据,该文件类似于以下矩阵/数组
b = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
我想将大于1的每个元素的索引更改为arraylist中的新行
这将使上面的数组如下
b = [[1,2],[5,6],[9,10],[3,4],[7,8][11,12]]
我在python中做了什么(但无法得到答案)
b = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
c = b
rows = len(b)
columns = len(b[0])
c[4].append(1)
count = 3
for i in range(rows):
for j in range(columns):
if i > 1:
for k in columns
list1 =
c.insert(count,list1)
count = count + 1
答案 0 :(得分:2)
您可以使用numpy
。最后执行indexing
和concatenate
:
import numpy as np
b = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(np.concatenate((b[:,:2], b[:,2:])))
# [[ 1 2]
# [ 5 6]
# [ 9 10]
# [ 3 4]
# [ 7 8]
# [11 12]]
答案 1 :(得分:0)
使用列表理解。
<强>实施例强>
b = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
n = 2
b = [j[i:i+n] for j in b for i in range(0, len(j), n)]
b = b[0::2] + b[1::2]
print(b)
<强>输出:强>
[[1, 2], [5, 6], [9, 10], [3, 4], [7, 8], [11, 12]]
答案 2 :(得分:0)
为什么不将它分成两个列表,然后重新组合它们?
new_elements = []
for i in range(len(b)):
if len(b[i]) > 2:
new_elements.append(b[i][2:])
b[i] = b[i][:2]
b.extend(new_elements)
答案 3 :(得分:0)
您可能希望使用numpy数组和concatenate函数。
import numpy as np
b = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) # or b = np.array(b)
c = np.concatenate((b[:, :2], b[:, 2:]),0)
如果您更喜欢使用python数组,可以使用列表解释:
c = [row[:2] for row in b]
c.extend([row[2:] for row in b])
返回
[[1, 2], [5, 6], [9, 10], [3, 4], [7, 8], [11, 12]]
答案 4 :(得分:0)
另一种方法是:
b = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
step = 2
length = len(b[0])
b = [elem[i:i+step] for i in range(0,length,step) for elem in b]
print(b)
输出:
[[1, 2], [5, 6], [9, 10], [3, 4], [7, 8], [11, 12]]
答案 5 :(得分:0)
data =[]
data.append(['a',1])
data.append(['b',2])
data.append(['c',3])
data.append(['d',4])
print(data)
[[''a',1],['b',2],['c',3],['d',4]]
答案 6 :(得分:0)
np.array(b).reshape(-1,2)
:import numpy as np
b = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
np.array(b).reshape(-1,2)
array([[ 1, 2],
[ 3, 4],
[ 5, 6],
[ 7, 8],
[ 9, 10],
[11, 12]])