简体   繁体   English

如何从列表列表中获取多个列表中项目的子序列?

[英]How to get a subsequence of items across multiple lists from a list of lists?

I am trying to get subsequence of items between 2 lists in a list of lists. 我试图在列表列表中的两个列表之间获取项目的子序列。 For example, if I have 例如,如果我有

list=[[1,2,3,4],[],[6,9],[2],[3],[4]]

I want to extract the items ranging from list[0][1] until list[2][1] into another list. 我想提取从list[0][1]list[2][1]到另一个列表。 This resulting list would then be [2,3,4,6] (ignoring the empty list in between). 这个结果列表将是[2,3,4,6] (忽略其间的空列表)。

How can I do that? 我怎样才能做到这一点? I have been trying to use a for i in range(...) loop but it is not working for me. 我一直试图for i in range(...)循环中使用for i in range(...)但它对我不起作用。

Assuming your list is called list_of_lists 1 , this list comprehension using enumerate() works: 假设您的列表名为list_of_lists 1 ,则使用enumerate() 列表理解有效:

[n for i, sub_list in enumerate(list_of_lists)
   for j, n in enumerate(sub_list)
   if (0, 1) <= (i, j) < (2, 1)]

1 It's a bad idea to call a list list as in your example, because that masks the name of the type list , which you then don't have access to. 1在您的示例中调用列表list是一个坏主意,因为这会掩盖类型list的名称,然后您无权访问该list

Try this: 尝试这个:

def complex_slice(my_list, i, j, k):
    result = my_list[i][k:]
    for sub_list in my_list[ (i + 1) : (j - 1) ]:
        result.extend(sub_list)
    result.extend(my_list[j][:k])
    return result

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM