【问题标题】:Making a list of lists from two lists based on indexes根据索引从两个列表中制作列表列表
【发布时间】:2018-05-06 16:46:32
【问题描述】:

我有这两个列表

indexes = [4, 2, 4, 6]
values = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]

我希望将这些列表合并成这样。每个索引值对应于合并的列表大小。

[[0, 1, 2, 3], [0, 1], [2, 3, 0, 1], [2, 3, 0, 1, 2, 3]]

我对此的当前答案还可以,但我想知道是否有更好的方法。

ids = []
cIndex = 0
for i in indexes:
    ids.append([values[cIndex+x] for x in xrange(i)])
    cIndex += i

【问题讨论】:

  • 您的代码生成[[0, 1, 2, 3], [0, 1], [2, 3, 0, 1], [2, 3, 0, 1, 2, 3]],这与相关列表不同。你到底想要什么?
  • 你说得对!
  • 与其他问题非常相似。请特别查看此答案:stackoverflow.com/a/312467/560599 - 不难将其概括为尺寸列表。

标签: python loops merge logic


【解决方案1】:

您可以将 list comprehension 表达式与list slicing 一起使用为:

>>> indexes = [4, 2, 4, 6]
>>> values = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]

>>> [values[sum(indexes[:i]):sum(indexes[:i+1])] for i, index in enumerate(indexes)]
[[0, 1, 2, 3], [0, 1], [2, 3, 0, 1], [2, 3, 0, 1, 2, 3]]

【讨论】:

  • 这是完美的。谢谢。
  • @chribis : 你在写问题时应该小心,一旦你得到答案,你不应该改变问题的基本要求。它将现有答案标记为无效答案。例如:我刚投了两票,因为你改变了你的问题:/ PS:我已经更新了答案以匹配你想要的结果
  • 很抱歉,@Moinuddin。我的错。我接受了你的回答。
  • 我很感激,但接受答案并不是道歉。在最初编写问题时,您需要小心。理想情况下,我应该将您的问题回滚到以前的版本。但既然你是新来的,我想你不知道,以后会小心的:)
【解决方案2】:
indexes = [4, 2, 4, 6]
values = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]

l=[]
l2=[]
j=0
for i in range(len(indexes)):
    k=0
    while k < indexes[i]:
        l.append(values[j])
        j+=1
        k+=1
    l2.append(l)
    l=[]

print(l2)

# [[0, 1, 2, 3], [0, 1], [2, 3, 0, 1], [2, 3, 0, 1, 2, 3]]

【讨论】:

    【解决方案3】:

    常规的 for 循环是一个可读的解决方案。不过,不需要列表理解,只需保持列表中的当前位置进行切片。

    def split(idxes, vals):
        res = []
        pos = 0
        for i in idxes:
            res.append(vals[pos:pos+i])
            pos += i
        return res
    

    或者,如果您特别想导入itertools,虽然这里并不真正需要,您可以获取索引的累积总和,然后使用pairwise 配方。

    from itertools import accumulate, tee
    
    def pairwise(iterable):
        "s -> (s0,s1), (s1,s2), (s2, s3), ..."
        a, b = tee(iterable)
        next(b, None)
        return zip(a, b)
    

    像这样

    >>> [values[beg:end] for beg, end in pairwise(accumulate([0]+indexes))]
    [[0, 1, 2, 3], [0, 1], [2, 3, 0, 1], [2, 3, 0, 1, 2, 3]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-24
      • 2023-02-23
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 2017-04-18
      相关资源
      最近更新 更多