【问题标题】:Generating a new order for a list of lists in python为python中的列表列表生成新顺序
【发布时间】:2015-09-29 10:17:24
【问题描述】:

我有一份想要重新排序的列表:

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]]

如果我有一个符合我想要的顺序的列表(例如here),我知道如何重新排序这个列表。棘手的部分是得到这个订单。

我拥有的是这样的:

locations = [(['Loc1','Loc1'], 3), (['Loc2'], 1), (['Loc3', 'Loc3', 'Loc3'], 2)]

这是一个元组列表,其中每个元组的第一个元素是一个带有位置名称的列表,该位置对每个人重复,第二个元素是这些人在qvalues 列表中的顺序(qvalues[0]'Loc2'qvalues[1:4]'Loc3'qvalues[4:6]'Loc1'

我想要将qvalues 中列表的顺序更改为它们在locations 中显示的顺序:首先是'Loc1',然后是'Loc2',最后是'Loc3'

这只是一个小例子,我的真实数据集有数百个人和 17 个位置。

提前感谢您提供的任何帮助。

【问题讨论】:

  • 这两个列表有什么关系?我在两个列表中都没有看到任何共同点
  • 抱歉,不清楚。 qvalues 的每个元素对应一个'LocX'qvalues 有六个元素,'LocX' 元素有六个。
  • 您对位置列表的解释含糊不清,请尝试给出输入和相应输出的示例。

标签: python list sorting tuples


【解决方案1】:

您需要建立一个偏移量和长度列表,而不是 locations 列表中提供的长度和位置。然后,您将能够根据您链接到的答案重新排序:

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输入列表一样吗?
  • @kezzos 哎呀,甚至没有注意我在计算什么。现在根据 OP 要求实际构建offsets 列表。
猜你喜欢
  • 2021-10-07
  • 1970-01-01
  • 1970-01-01
  • 2013-10-30
  • 1970-01-01
  • 2013-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多