[英]lists: index of lowest value and reorder
我有一個這樣的列表:
foo =
[[a1, a2, a3, a4, a5],
[b1, b2, b3, b4, b5],
[c1, c2, c3, c4, c5]]
# in real: many more rows & columns
每個a_i,b_i和c_i包含3個值:[x,y,z]
現在我想以這種方式重新排序:我希望獲得a-column的索引,其中我的y值最低。 讓我們說,例如,在a3中,所有a的y值都是最低的。 所以我想以這種方式重新排序我的列表:
[[a3, a4, a5, a1, a2],
[b3, b4, b5, b1, b2],
[c3, c4, c5, c1, c2]]
- >所以我不關心其他的y值,只想知道最低的值並將其設置在我的列表的第一個位置並保持序列(在a3之后a4之后的a5 ......)活着 - >在a3(a1和a2)之前的原始列表中的位置最后應附加的值。
我知道我可以得到第一列的最低y值:
xmin, ymin, zmin = map(min, zip(*foo[0]))
print ymin
但我不需要值,而是索引。 如何在沒有for-loop的情況下重新排序列表?
編輯:沒有使用for循環的原因:這是一個巨大的列表,我正在尋找一種更有效的方法。 但我也會接受一個for循環。
你可以找到合適的索引然后使用列表理解:
from operator import itemgetter
# first get index from first row
min_index = min(enumerate(foo[0]), key=lambda x: x[1][1])[0]
# then apply to all rows
foo = [item[min_index:] + item[:min_index] for item in foo]
請注意,這將循環,但您編寫的任何代碼都會在某些時候執行此操作!
你有一份清單清單; 我假設外部列表保持不變。
for row in foo:
row.sort(key=lambda x:min(*x))
主要的內容是用lambda鍵排序, min(*x)
取列表x中所有值的min
你必須循環foo,但這是可以預料的。
一個基於numpy的解決方案。
import numpy as np
foo = np.random.randint(0,100,(3,5)) #some random data for testing
print foo #original order
i = np.argmin(foo[1,:]) #find min index of second row
foo[:,[0,i]] = foo[:,[i,0]] #swap columns to move selected row to front
print foo #new order
或者,如果您決定要對整行進行排序,並且不介意稍高的計算負荷:
import numpy as np
foo = np.random.randint(0,100,(3,5)) #some random data for testing
print foo #original order
foo = foo[:,np.argsort(foo[1])] #complete sorting by second row
print foo #new order
無論哪種方式,在性能方面,這兩者都將從水中吹出純粹的基於python的解決方案。
簡單:按第一個元素對列進行排序,沿對角線翻轉,按第一個元素對行進行排序,然后翻轉。
def diagFlip(grid):
return [[grid[i][j] for i in range(len(grid))] for j in range(len(grid[0]))]
def sortByColumnTops(grid):
grid = diagFlip(grid)
grid.sort(key=(lambda row: row[0][1]))
return diagFlip(grid)
並證明它的工作原理:
test = [[[0,4,0],[0,2,0],[0,3,0],[0,1,0]],
[[0,1,0],[0,3,0],[0,2,0],[0,4,0]],
[[0,1,0],[0,2,0],[0,3,0],[0,4,0]]]
test = sortByColumnTops(test)
for row in test: print(row)
產量
[[0, 1, 0], [0, 2, 0], [0, 3, 0], [0, 4, 0]]
[[0, 4, 0], [0, 3, 0], [0, 2, 0], [0, 1, 0]]
[[0, 4, 0], [0, 2, 0], [0, 3, 0], [0, 1, 0]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.