【发布时间】:2021-05-19 08:30:04
【问题描述】:
我有这个清单:
list_to_modify = [[296.0, 277.0, 1560.0, 361.0],
[1958.0, 595.0, 2059.0, 674.0],
[291.0, 573.0, 371.0, 882.0],
[1957.0, 696.0, 2058.0, 777.0],
[1959.0, 797.0, 2060.0, 876.0],
[1964.0, 490.0, 2063.0, 573.0],
[298.0, 1084.0, 785.0, 1235.0],
[300.0, 1423.0, 371.0, 1729.0],
[1631.0, 1614.0, 2067.0, 1728.0],
[304.0, 1810.0, 790.0, 1961.0],
[1438.0, 1902.0, 2065.0, 2014.0],
[1384.0, 2075.0, 1887.0, 2194.0],
[997.0, 2241.0, 1099.0, 2319.0],
[1392.0, 2331.0, 2010.0, 2447.0],
[999.0, 2341.0, 1100.0, 2419.0],
[997.0, 2441.0, 1100.0, 2519.0],
[999.0, 2542.0, 1100.0, 2619.0]]
如果element[0] 与数组中的其他element[0] 相似,我想选择元素。顺序很重要,所以我只需要将数组修改为块。这样就变成了这样:
desired_list = [[296.0, 277.0, 1560.0, 361.0],
[1964.0, 490.0, 2063.0, 573.0],
[291.0, 573.0, 371.0, 882.0],
[1958.0, 595.0, 2059.0, 674.0],
[1957.0, 696.0, 2058.0, 777.0],
[1959.0, 797.0, 2060.0, 876.0],
[298.0, 1084.0, 785.0, 1235.0],
[300.0, 1423.0, 371.0, 1729.0],
[1631.0, 1614.0, 2067.0, 1728.0],
[304.0, 1810.0, 790.0, 1961.0],
[1438.0, 1902.0, 2065.0, 2014.0],
[1384.0, 2075.0, 1887.0, 2194.0],
[997.0, 2241.0, 1099.0, 2319.0],
[1392.0, 2331.0, 2010.0, 2447.0],
[999.0, 2341.0, 1100.0, 2419.0],
[997.0, 2441.0, 1100.0, 2519.0],
[999.0, 2542.0, 1100.0, 2619.0]]
我不能在这里使用常规排序,因为这些是来自图像输入的坐标,所以如果我这样排序:
sorted(list_to_modify, key=lambda x: x[1])
由于不是每张图片都是相同的,这会导致问题。例如我需要把它当作一个块:
chunk = [1958.0, 595.0, 2059.0, 674.0],
[1957.0, 696.0, 2058.0, 777.0],
[1959.0, 797.0, 2060.0, 876.0],
[1964.0, 490.0, 2063.0, 573.0],
并按第二项排序:
chunk = sorted(chunk, key=lambda x:x[1])
然后使用新索引再次将其插入列表。因为最后一项现在是第一项。我需要使用原始列表中第一项的索引并将最后一项插入到第一项的位置(如果令人困惑,请查看desired_list,您会明白我的意思)。
我已经来了这么远:
temporary=[]
dummy_list = [None] * len(ilk)
for x in list_to_modify:
if list_to_modify.index(x) != 0: #I don't want to touch the first item
val = x[0]
first_cond = val - 20
second_cond = val + 20
for y in list_to_modify:
if list_to_modify.index(y) != 0 and y[0]>first_cond and y[0]<second_cond :
if y in temporary:
pass
else:
temporary.append([list_to_modify.index(y),y])
temporary= sorted(temporary, key=lambda x:x[1][1])
newlist=[]
for i in temporary:
if i not in newlist:
newlist.append(i)
这就是结果:/
[[5, [1964.0, 490.0, 2063.0, 573.0]],
[2, [291.0, 573.0, 371.0, 882.0]],
[1, [1958.0, 595.0, 2059.0, 674.0]],
[3, [1957.0, 696.0, 2058.0, 777.0]],
[4, [1959.0, 797.0, 2060.0, 876.0]],
[6, [298.0, 1084.0, 785.0, 1235.0]],
[7, [300.0, 1423.0, 371.0, 1729.0]],
[8, [1631.0, 1614.0, 2067.0, 1728.0]],
[9, [304.0, 1810.0, 790.0, 1961.0]],
[10, [1438.0, 1902.0, 2065.0, 2014.0]],
[11, [1384.0, 2075.0, 1887.0, 2194.0]],
[12, [997.0, 2241.0, 1099.0, 2319.0]],
[13, [1392.0, 2331.0, 2010.0, 2447.0]],
[14, [999.0, 2341.0, 1100.0, 2419.0]],
[15, [997.0, 2441.0, 1100.0, 2519.0]],
[16, [999.0, 2542.0, 1100.0, 2619.0]]]
不知何故,我需要在不使用 .sort 方法的情况下达到与 desired_list 相同的结果。
【问题讨论】:
标签: python arrays python-3.x numpy sorting