如何解决交换被翻转的数组元素的有效方法
假设您有一组有机会对称翻转的点(如下所示)
from matplotlib import pyplot as plt
import numpy as np
# Data
a = np.array([0.1,-0.325,-0.55,0.775,1]) # x-axis
b = np.array([10,-3.077,-1.818,1.2903,1]) # y-axis
c = np.array([-0.1,0.325,0.55,-0.775,-1]) # x-axis
d = np.array([-10,3.077,1.818,-1.2903,-1])# y-axis
y = [a,b,c,d] # The array is created this way intentionally for when I apply it to my case
plt.plot(y[0],y[1],'k.')
plt.plot(y[2],y[3],'r.')
plt.show()
假设我们知道它应该具有什么形式,我如何自动检查每个数组元素并编写一个条件来纠正这些点的位置?
编辑:
这是我想要得到的图表
解决方法
这个例子会起作用
a = np.absolute(a)
b = np.absolute(b)
c = -np.absolute(c)
d = -np.absolute(d)
但其他情况可能需要 minus
用于不同的列表。因此,识别哪个列表需要减去可能是一个大问题。
更好的方法是创建对 (x,y)
并通过 x > 0
x < 0
(或 y > 0
y < 0
)将它们拆分为两个列表,然后将对转换回列出 x
和 y
(也许使用 numpy 可以更轻松、更快地完成)
all_pairs = list(zip(a,b)) + list(zip(c,d))
# ---
lower = []
higher = []
for pair in all_pairs:
if pair[0] > 0:
higher.append(pair)
else:
lower.append(pair)
# ---
a,b = list(zip(*higher))
c,d = list(zip(*lower))
最少的工作代码
import numpy as np
import matplotlib.pyplot as plt
# Data
a = np.array([0.1,-0.325,-0.55,0.775,1]) # x-axis
b = np.array([10,-3.077,-1.818,1.2903,1]) # y-axis
c = np.array([-0.1,0.325,0.55,-0.775,-1]) # x-axis
d = np.array([-10,3.077,1.818,-1.2903,-1])# y-axis
all_pairs = list(zip(a,d))
print(all_pairs)
higher = []
lower = []
for pair in all_pairs:
if pair[0] > 0:
higher.append(pair)
else:
lower.append(pair)
print(higher)
print(lower)
a,d = list(zip(*lower))
y = [a,b,c,d] # The array is created this way intentionally for when I apply it to my case
#plt.plot(y[0],y[1],'k.')
#plt.plot(y[2],y[3],'r.')
plt.plot(*y[0:2],'k.')
plt.plot(*y[2:4],'r.')
plt.show()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。