Python在列表中排序数据

时间:2017-03-08 14:04:48

标签: python list sorting append

我们有三个不同的列表:

1th = [(442, 248), (442, 249), (442, 250), (442, 251), (442, 252), (442, 253), (442, 254), (442, 255), (442, 256), (442, 257), (442, 258), (442, 259), (442, 260), (442, 261)]
2nd = [(96, 128, 144), (112, 128, 144), (80, 96, 96), (32, 48, 48), (64, 64, 64), (64, 64, 64), (32, 32, 32), (16, 16, 0), (16, 16, 0), (16, 16, 0), (16, 16, 0), (16, 16, 16), (32, 32, 32)]
3-rd = [(16, 16, 16), (32, 32, 32)]

程序需要从第3个列表中取一个值(我们称之为“ Etalon ”值),将其与来自第二个列表的数据进行比较,如果相同,则必须使用列表中的索引取值2和取值程序必须在Etalon之后添加到列表3中。

结果必须如下:

[((16, 16, 16), (442, 255), (442, 256), (442, 257), (442, 258)), ((32, 32, 32),(442, 248), (442, 249), (442, 250))]

上面的所有数据都是RGB颜色,xy坐标和提示将像素分类为颜色。

问题是:需要使用哪种方法将元素添加到具有特定索引的第3个列表?我尝试了以下方法,但它不起作用:

3-rd.append(1th[index from 2nd])

3 个答案:

答案 0 :(得分:0)

Python有一个insert()方法,允许您在列表中的特定索引处插入元素。

list_name = ["a", "b", "d"]

list_name.insert(2,"d")

print list_name

#prints ['a', 'b', 'd', 'd']

答案 1 :(得分:0)

尝试以下方法:

first = [(442, 248), (442, 249), (442, 250), (442, 251), (442, 252), (442, 253), (442, 254), (442, 255), (442, 256), (442, 257), (442, 258), (442, 259), (442, 260), (442, 261)]
second = [(96, 128, 144), (112, 128, 144), (80, 96, 96), (32, 48, 48), (64, 64, 64), (64, 64, 64), (32, 32, 32), (16, 16, 16), (16, 16, 16), (16, 16, 16), (16, 16, 0), (16, 16, 16), (32, 32, 32)]
third = [(16, 16, 16), (32, 32, 32)]            

output = []

for v3 in third:
    f = True
    run = []
    for i2, v2 in enumerate(second):
        if v3 == v2:
            if f:
                run.append(v3)
                f = False

            run.append(first[i2])

    if run:
        output.append(run)

print output            

这会产生输出:

[[(16, 16, 16), (442, 255), (442, 256), (442, 257), (442, 259)], [(32, 32, 32), (442, 254), (442, 260)]]    

答案 2 :(得分:0)

maxDuration