Python对列表中的数据进行排序
我们有三个不同的清单:Python对列表中的数据进行排序,python,list,sorting,append,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,
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)]
一个程序需要从第三个列表中获取一个值(我们称之为“标准具””值),将其与第二个列表中的数据进行比较,如果它必须从列表2中的索引中获取值,那么获取的值程序必须在标准具之后添加到列表3中
结果必须如下所示:
[((16, 16, 16), (442, 255), (442, 256), (442, 257), (442, 258)), ((32, 32, 32),(442, 248), (442, 249), (442, 250))]
上面的所有数据都是RGB颜色、xy坐标和按颜色排序像素的提示
问题是:需要使用哪种方法将元素添加到具有特定索引的第三个列表中?我尝试了以下方法,但无效:
3-rd.append(1th[index from 2nd])
Python有一个insert()方法,允许您在列表中的特定索引处插入元素
list_name = ["a", "b", "d"]
list_name.insert(2,"d")
print list_name
#prints ['a', 'b', 'd', 'd']
请尝试以下操作:
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)]]
“不是我所需要的”。。。您能发布您得到的任何错误或不正确的输出吗?3-rd.append(第1个[第2个索引])需要[(16,16,16),(32,32,32),(442,248),(442,249),(442,250),(442,251),(442,252)]e.q[RGB,RGB,XY,XY,XY]需要[RGB,XY,XY,XY,RGB XY,XY]尽管这些都是最可能的示例,
1th
,2nd
和3-rd
在Python中不是有效的变量名。请阅读第1、2、3条,读作“第一个python列表”、“第二个”等等
import pandas as pd
first = pd.Series([(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 = pd.Series([(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)]
res = [ [item] + first[ second[ second == item].index ].tolist() for item in third]
[[(16, 16, 16), (442, 255), (442, 256), (442, 257), (442, 259)], [(32, 32, 32), (442, 254), (442, 260)]]