很抱歉我没有想到更好的问题标题。
我有两个等长的列表,例如:
a = [True, False, False, True, True, False, False, True]
b = [1, 2, 2, 1, 1, 3, 3, 2 ]
i j i' j'
我希望调整列表a
,使得当从索引i
到j
的列表a
中存在一个或多个连续的False
时,按照以下条件进行调整:
if b[i-1]==b[j+1]:
a[i:j+1]=[True]*(j-i+1)
在上面的示例中,有两个这样的块:
i,j=1,2
和 i',j'=5,6
。
结果应该是:a = [True, True, True, True, True, False, False, True]
我用for
循环和if
语句写了一个解决方案,但是由于我想在非常大的列表上使用它,所以速度太慢。
a = [True, False, False, True, True, False, False, True]
b = [1, 2, 2, 1, 1, 3, 3, 2 ]
#Edit: the next two lines were originally and wrongly inside the for loop
moving=True
istart=1
for i,trp in enumerate((a)):
if trp==False:
if moving==False:
# if this condition holds, the particle just started a new move
istart = i
moving = True
else:
if moving==True:
# is this condition holds, the particle has stopped its move
moving = False
if b[i]==b[istart-1]:
# if this holds, a needs to be adjusted
a[istart:i]=[True]*(i-istart)
非常感谢您的帮助。 (由于它是用于分析物理模拟,因此注释和变量名称就像那样)
itertools
可以起到作用。另外一种方法是将它改写成编译型语言,例如C、C++或Java。纯Python相比这些语言本质上更慢,写一小段代码可能就能解决你的问题。 - dantiston