[英]Efficient way to swap array elements that are flipped
假設您有一組點有機會對稱翻轉(如下所示)
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()
假設我們知道它應該具有什么形式,我如何自動檢查每個數組元素並編寫一個更正這些點的 position 的條件?
編輯:
這是我想要得到的圖表
對於此示例將起作用
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,b)) + list(zip(c,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, b = list(zip(*higher))
c, 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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.