简体   繁体   English

Append x 第一次出现在列表中并中断循环。 但是,如果 y 出现在 x 之前,append y 第一次出现,则忽略 y 直到 x 第一次出现

[英]Append 1st occurence of x to a list and break loop. However, if y occurs before x, append 1st occurrence of y, then ignore y until 1st occurence of x

I am iterating through a column in multiple dataframes df1['values'] , df2['values'] , and so on.我正在遍历多个数据帧df1['values']df2['values']等中的一列。 The elements in ['values'] look like this: ['values']中的元素如下所示:

[3, 1, 3, 1, 1, 4, 4, 3, 3, 1, 2, 1, 1, 3, 4, 2, 3, 1, 1, 1]

I want to loop through the column and append the first occurrence of 4 to a new list and break the loop.我想遍历列和 append 第一次出现的 4 到一个新列表并中断循环。 However, if 3 occurs before 4, then I want to append that 1st occurrence of 3, ignore any subsequent occurrence of 3, but continue looping until I get to the first occurrence of 4, then break the loop.但是,如果 3 出现在 4 之前,那么我想要 append 第一次出现 3,忽略 3 的任何后续出现,但继续循环直到我到达 4 的第一次出现,然后中断循环。

So, with the list above: [3, 1, 3, 1, 1, 4, 4, 3, 3, 1, 2, 1, 1, 3, 4, 2, 3, 1, 1, 1]因此,对于上面的列表: [3, 1, 3, 1, 1, 4, 4, 3, 3, 1, 2, 1, 1, 3, 4, 2, 3, 1, 1, 1]

Desired output would be: [3,4]所需的 output 将是: [3,4]

But if the list looked like: [2, 1, 2, 1, 1, 4, 4, 3, 3, 1, 2, 1, 1, 3, 4, 2, 3, 1, 1, 1]但是如果列表看起来像: [2, 1, 2, 1, 1, 4, 4, 3, 3, 1, 2, 1, 1, 3, 4, 2, 3, 1, 1, 1]

Desired output would be: [4]所需的 output 将是: [4]

You could do it like this:你可以这样做:

u = df['values'].unique()
u = u[u >= 3]
u = u[:(u == 4).argmax()+1]

Output (using first list): Output(使用第一个列表):

>>> u
array([3, 4])

Output (using second list): Output(使用第二个列表):

>>> u
array([4])

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

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