Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中为列表列表生成新顺序_Python_List_Sorting_Tuples - Fatal编程技术网

在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要求构建了
偏移量
列表。