简体   繁体   English

嵌套 for 循环的列表理解

[英]List comprehension on nested for loop

I have a list:我有一个清单:

l1 = [1,2,3,6,8,1,2,3]

I want to iterate over list and print list of numbers starting and ending with same number.I have done it with for loop:我想遍历列表并打印以相同数字开头和结尾的数字列表。我用 for 循环完成了它:

iniatializing = 1
for i in l1:
 for j in range(iniatializing,len(l1)):
     if i == l1[j]:
         starting_point =l1.index(i)
         print(l1[starting_point:j+1])
     iniatializing += 1

But how can this be done by using list comprehension?但是如何通过使用列表推导来做到这一点?

I suppose what you want to achieve is:我想你想要实现的是:

For each i , j ( i < j ), if l1[i]==l2[j] , print the subset between i and j .对于每个i , j ( i < j ),如果l1[i]==l2[j] ,则打印ij之间的子集。

n = len(l1)
[l1[i:j+1] for i in range(n) for j in range(i+1, n) if l1[i] == l1[j]]

EDIT: answer to the question about the original implementation.编辑:回答有关原始实现的问题。

l1 = [1,2,3,6,8,1,2,3]

iniatializing = 1
for i in l1:
 for j in range(iniatializing,len(l1)):
     if i == l1[j]:
         starting_point =l1.index(i)
         print(l1[starting_point:j+1])
 iniatializing += 1

#[1, 2, 3, 6, 8, 1]
#[2, 3, 6, 8, 1, 2]
#[3, 6, 8, 1, 2, 3]

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

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