Python,使用条件附加到列表

Python, appending to a list using conditions

我有一个包含两列的文件,假设是 A 和 B

A     B
1     10
0     11
0     12 
0     15
1     90
0     41

我想创建一个新列(列表),让我们调用空列表C = []

我想遍历 A,查找是否 A == 1,如果是,我想将 B[A==1] 的值(第一种情况下为 10)附加到 C 直到下一个 A == 1 到达。

所以我的最终结果是:

A     B     C
1     10    10
0     11    10
0     12    10
0     15    10
1     90    90
0     41    90

我尝试过使用 for 循环,但令我沮丧的是:

for a in A:
    if a == 1:
        C.append(B[a==1])
    elif a == 0:
        C.append(B[a==1])

您可以使用另一个变量来保留 A 中最后一个值为 1 的索引的值,并在满足条件时更新它:

temp = 0
for index, value in enumerate(A):
    if value == 1:
        C.append(B[index])
        temp = index
    else:
        C.append(B[temp])

enumerate() 为您提供了一个元组列表,其中包含来自可说对象的索引和值。 对于 A,它将是 [(0, 1), (1, 0), (2, 0), (3, 0), (4, 1), (5, 0)].

P.S:当您尝试使用布尔值 (B[a == 1]) 寻址列表时,如果条件为假 (B[a != 1] => B[False] => B[0]) 或第二位的项目(如果为真)(B[a == 1] => B[True] => B[1]).

您也可以尝试使用 groupby

虽然我想出的解决方案对我来说有点令人费解:

>>> from itertools import izip, groupby, count
>>> from operator import itemgetter
>>> def gen_group(L):
    acc = 0
    for item in L:
        acc += item
        yield acc


>>> [number_out for number,length in ((next(items)[1], 1 + sum(1 for _ in items)) for group,items in groupby(izip(gen_group(A), B), itemgetter(0))) for number_out in repeat(number, length)]
[10, 10, 10, 10, 90, 90]

想法是准备组,然后使用它们对您的输入进行分组:

>>> list(gen_group(A))
[1, 1, 1, 1, 2, 2]