在python中为列表列表生成新顺序
我有一个要重新排序的列表:在python中为列表列表生成新顺序,python,list,sorting,tuples,Python,List,Sorting,Tuples,我有一个要重新排序的列表: qvalues = [[0.1, 0.3, 0.6],[0.7, 0.1, 0.2],[0.3, 0.4, 0.3],[0.1, 0.3, 0.6],[0.1, 0.3, 0.6],[0.1, 0.3, 0.6]] 如果我有一个具有我想要的顺序的列表,我知道如何对该列表重新排序(示例)。棘手的部分是得到这个订单 我所拥有的是: locations = [(['Loc1','Loc1'], 3), (['Loc2'], 1), (['Loc3', 'Loc3', 'L
qvalues = [[0.1, 0.3, 0.6],[0.7, 0.1, 0.2],[0.3, 0.4, 0.3],[0.1, 0.3, 0.6],[0.1, 0.3, 0.6],[0.1, 0.3, 0.6]]
如果我有一个具有我想要的顺序的列表,我知道如何对该列表重新排序(示例)。棘手的部分是得到这个订单
我所拥有的是:
locations = [(['Loc1','Loc1'], 3), (['Loc2'], 1), (['Loc3', 'Loc3', 'Loc3'], 2)]
这是一个元组列表,其中每个元组的第一个元素是带有位置名的列表,对该位置中的每个个体重复,第二个元素是这些个体在qvalues
列表中的顺序(qvalues[0]
是'Loc2'
,qvalues[1:4]
是'Loc3'
和qvalue[4:6]
是'Loc1'
我想要的是将qvalues
中列表的顺序更改为它们在位置中显示的顺序:首先'Loc1'
,然后'Loc2'
,最后'Loc3'
这只是一个小例子,我的真实数据集有数百个人和17个位置
提前感谢您提供的帮助。您需要建立偏移量和长度列表,而不是位置列表中提供的长度和位置。然后,您可以根据链接到的答案重新排序:
qvalues = [[0.1, 0.3, 0.6],[0.7, 0.1, 0.2],[0.3, 0.4, 0.3],[0.1, 0.3, 0.6],[0.1, 0.3, 0.6],[0.1, 0.3, 0.6]]
locations = [(['Loc1','Loc1'], 3), (['Loc2'], 1), (['Loc3', 'Loc3', 'Loc3'], 2)]
locations_dict = {pos:(index,len(loc)) for index,(loc,pos) in enumerate(locations)}
# if python2: locations_dict = dict([(pos,(index,len(loc))) for index,(loc,pos) in enumerate(locations)])
offsets = [None]*len(locations)
def compute_offset(pos):
# compute new offset from offset and length of previous position. End of recursion at position 1: we’re at the beginning of the list
offset = sum(compute_offset(pos-1)) if pos > 1 else 0
# get index at where to store current offset + length of current location
index, length = locations_dict[pos]
offsets[index] = (offset, length)
return offsets[index]
compute_offset(len(locations))
qvalues = [qvalues[offset:offset+length] for offset,length in offsets]
最后,您将看到qvalues
是一个列表列表,而不是一个“简单”的列表列表。如果您想将其展平以保持初始布局,请使用此列表:
qvalues = [value for offset,length in offsets for value in qvalues[offset:offset+length]]
输出第一个版本
[[[0.1, 0.3, 0.6], [0.1, 0.3, 0.6]], [[0.1, 0.3, 0.6]], [[0.7, 0.1, 0.2], [0.3, 0.4, 0.3], [0.1, 0.3, 0.6]]]
第二版本的输出
[[0.1, 0.3, 0.6], [0.1, 0.3, 0.6], [0.1, 0.3, 0.6], [0.7, 0.1, 0.2], [0.3, 0.4, 0.3], [0.1, 0.3, 0.6]]
这两个列表之间的关系是什么?我看不出两个列表中有什么共同之处。不清楚。qvalues
的每个元素都对应一个'LocX'
。在qvalues
中有六个元素,还有六个'LocX'
元素。您对位置列表的解释很模糊,试着举例说明输入和相应的输出。输出与qvalues输入列表相同?@kezzos哎呀,我甚至没有注意到我在计算什么。实际上,现在根据OP要求构建了偏移量列表。