如何在列表中定义数组?

2024-05-15 12:14:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码片段,如下所示。我希望在执行代码后,原始数组值(如x1、x2、y1和y2数组等)会相应地更改,而这目前还没有发生。有没有办法做到这一点??。与当前代码执行后一样,x1数组值保持不变,我希望它们应该相应地更改,因为list1[0]数组值在代码执行后发生更改

import numpy as np
x1=np.array([10,2,10,5,10,7,10,6])
y1=np.array([2,3,6,5,8,9,7,8])
r1=np.array([0,4,0,3,0,5,0,3])
x2=np.array([10,3,10,6,10,8,10,7])
y2=np.array([2,3,6,5,8,9,7,8])
r2=np.array([0,5,0,7,0,9,0,3])
list1=[x1,x2]
list2=[y1,y2]
list3=[r1,r2]
for plane in range(0,2):
    x=list1[plane]
    y=list2[plane]
    r=list3[plane]
    comb=np.array([x,y,r])
    comb=np.transpose(comb)
    combsort=comb[np.argsort(comb[:,0])]
    combsort=combsort.transpose()
    x=combsort[0]
    y=combsort[1]
    r=combsort[2]
    ind1=np.where(x==10)
    ind2=ind1[0]
    if(ind2.size):
        indd=ind2[0]
    x[indd:indd+len(ind2)]=np.ones(len(ind2))
    y[indd:indd+len(ind2)]=np.ones(len(ind2))
    r[indd:indd+len(ind2)]=np.ones(len(ind2)) 
    list1[plane]=x
    list2[plane]=y
    list3[plane]=r
    
print(x1)   
print(list1[0])

输出

[10  2 10  5 10  7 10  6]
[2 5 6 7 1 1 1 1]

Tags: lennp数组arrayx1x2comblist2
2条回答

更简单的情况是:

In [63]: x=np.array([1,2,3])
In [64]: alist = [x]
In [65]: alist
Out[65]: [array([1, 2, 3])]
In [66]: alist[0]
Out[66]: array([1, 2, 3])
In [67]: alist[0][:] = [4,5,6]     # this changes elements of the array
In [68]: alist
Out[68]: [array([4, 5, 6])]
In [69]: x
Out[69]: array([4, 5, 6])

这会将列表的元素更改为具有不同大小的列表

In [70]: alist[0]=[7,8]
In [71]: alist
Out[71]: [[7, 8]]
In [72]: x
Out[72]: array([4, 5, 6])

您可以使用numpy的column stack

np.column_stack((x1, y1))

相关问题 更多 >