【发布时间】:2022-12-03 10:11:06
【问题描述】:
我有 3 个列表:
在逗号之间添加空格,以便更好地理解我将使用的 groupby。
a=[1,1,1,1 ,2,2,2 ,3,3,3,3,3,3, 4,4]
b=['l2','l5','l1','l1' ,'l5','l2','' , 'l1','l3','l6','l2','l5','l1' , 'l5','l1']
c=['z','z','a','s' ,'z','z','a', 's','z','z','a','s','d' , 's','' ]
在列表“a”中,我有一些组,根据这些组,我想在列表“c”中相对于列表“b”进行更改。
列表 'a' 有 1 组,所以对于那些 1 的索引,我正在检查列表 'b' 并且无论我在哪里找到字符串 'l5',我都想让该组的所有进一步索引在列表中为空字符串( '' ) 'C'。
例如:
If list 'a' has [1,1,1,1] and list b has ['l2','l5','l1','11'].
我想在 'l5' 之后创建索引,即列表 c 中的索引 2 和 3 为空。
列表 c 的预期输出为:
c= ['z','z','','']
我为此编写了一个代码,它工作得很好,但我认为这在 O(n^2) 的时间复杂度内有效。有什么方法可以优化此代码并使其在 O(n) 时间内运行以使其更快?
这是我的代码:
a=[1,1,1,1 ,2,2,2 ,3,3,3,3,3,3, 4,4]
b=['l2','l5','l1','l1' ,'l5','l2','' , 'l1','l3','l6','l2','l5','l1' , 'l5','l1']
c=['z','z','a','s' ,'z','z','a', 's','z','z','a','s','d' , 's','' ]
from itertools import groupby
g= groupby(a)
m=0
for group,data in g:
n = len(list(data)) #length of each group
m+=n #this stores the sum of length of groups (To get the last index of each group)
while m:
h=m-n #to get the beginning index of each group(total-length_of_currentgroup)
nexxt=0
for i in range(h,m): #this loops for each group (where h is start and m is ending index of each group)
if b[i]=='l5' and nexxt==0:
nexxt=i+1
while nexxt<m and nexxt!=0:
c[nexxt] = ''
nexxt+=1
break
print(c)
输出:
['z', 'z', '', '', 'z', '', '', 's', 'z', 'z', 'a', 's', '', 's', '']
有没有办法在 O(N) 时间内写这个?
【问题讨论】:
标签: arrays algorithm data-structures stack time-complexity