[英]Need help understanding how a line of code is using a maximum y coordinate to find the corresponding X value in python
我有一個腳本,循環遍歷每行 42 個 X 和 Y 坐標,並找到對應於該行中最高 Y 值的 X 坐標。 如果 X 值對應於最高的 Y,則返回 1(真),否則返回 0。
一切正常。 我只是有點困惑為什么它有效。 我將發布腳本中的相關代碼部分,然后討論我之后感到困惑的部分。
for row in reader:
vals = row[0:84]
vals = [float(v) for v in vals] # convert from strings to floats
max_i = np.nanargmax(vals[1::2]) # go from index 1 in steps of 2, ie. only the y values, and find the max y value. Ignore NA results.
fan_line = 0
for i in range(0,84,2): # go through x values
fan_line += 1
max_y = 1 if max_i*2 == i else 0 # note, it's max_i*2 because max_i is the index in just the y list (vals[1::2])
令我困惑的一行是:
max_y = 1 if max_i*2 == i else 0 # note, it's max_i*2 because max_i is the index in just the y list
我知道#后面有一個解釋,但老實說,我不明白。 寫劇本的人曾向我解釋過一次,這很有道理,但他們不再是我部門的一部分。 我真的很想知道到底發生了什么,以防它對未來的項目有用。 我理解代碼的其余部分,但那一行讓我感到困惑。
編輯
抱歉,我應該澄清一下我不明白的是什么。 我不知道max_i*2 == i
在做什么。 max_i*2
與“i”有什么關系?
這是python中的三元運算符: https : //docs.python.org/3/reference/expressions.html#conditional-expressions
線
max_y = 1 if max_i*2 == i else 0
相當於
if max_i*2 == i:
max_y = 1
else:
mas_y = 0
在max_i = np.nanargmax(vals[1::2])
它構造一個具有每隔一個值的數組,然后在該“每隔一個值”數組中找到最大值的位置。
為了得到原始數組中的位置,我們需要將其乘以二(並加一)。
例如:
>>> alphabet
'abcdefghijklmnopqrstuvwxyz'
>>> alphabet[1::2]
'bdfhjlnprtvxz'
>>> alphabet[1::2].index('j')
4
>>> alphabet[4*2 + 1]
'j'
>>>
重構建議:為了讓代碼不那么混亂,第一時間將數據轉換為元組列表; 通過使用more_itertools.chunked
或points = list(zip(vals[0::2], vals[1::2]))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.