简体   繁体   English

有while循环时替换列表的值

[英]Replacing the values of a list whilst there is a while loop

So say I have ['habcuxabc929abc', 'tabc', 'q', 'jabcuabc9'] . 所以说我有['habcuxabc929abc', 'tabc', 'q', 'jabcuabc9']

What I basically want to do is split each element in this list between the abc 's and count the remaining parts. 我基本上想要做的是将此列表中的每个元素拆分为abc并计算其余部分。 So the list specified above would look like: [3, 1, 1, 3] . 所以上面指定的列表看起来像: [3, 1, 1, 3] What I have done does that but the main thing I want to achieve is if this value is less than 2 then it removes all abc 's and replaces them with q 's. 我做了什么,但我想要实现的主要是如果这个值小于2然后它删除所有abc并用q替换它们。 (This works so far, although it is probably not pythonic). (到目前为止,虽然它可能不是pythonic)。 If the value is greater than 2 then I just want it to remove the last 'abc' and replace it with q , leaving all the previous abc 's as they are but I don't know how to do this, any suggestions would be greatly appreciated. 如果该值大于2,那么我只是想要它删除最后一个'abc'并用q替换它,留下所有先前的abc原样,但我不知道该怎么做,任何建议都是不胜感激。

while n < len(list123):
    dummylist = [len(r.split('abc')) for r in list123]

    if dummylist[n] <= 2:
        print 'true'
        list123 = [i.replace('abc',' q ') for i in list123]
        n=n+1
    elif dummylist[n] > 2:
        print 'false'
        list123 = [i.replace('abc',' q ') for i in list123]
        n=n+1

Thanks! 谢谢!

Firstly, a while loop is the wrong choice here, and having the split inside it seems ludicrous. 首先, while循环是错误的选择,在这里,和具有split 里面看起来很荒唐。

Secondly, you don't want to replace all of the items in list123 if any happen to have fewer than two parts; 其次,如果碰巧有少于两个部分,你不想replace list123所有项目; only modify list123[i] as you iterate over each index i . 当你迭代每个索引i只修改list123[i]

Thirdly, to remove only the last 'abc' you can use str.rsplit and specify a maximum of one splits, then str.join back together with 'q' instead. 第三,要仅删除最后一个'abc'您可以使用str.rsplit并指定最多一个分割,然后str.join'q'一起返回。

This is much neater: 这个更整洁:

dummylist = [len(r.split('abc')) for r in list123]
for i, n in enumerate(dummylist):
    if n <= 2:
        list123[i] = list123[i].replace('abc', 'q')
    else:
        list123[i] = 'q'.join(list123[i].rsplit('abc', 1))

This gives me list123 == ['habcuxabc929q', 'tq', 'q', 'jabcuq9'] . 这给了我list123 == ['habcuxabc929q', 'tq', 'q', 'jabcuq9']

If I understand you correctly, it looks like you want something close to: 如果我理解正确,看起来你想要一些接近的东西:

lst = ['habcuxabc929abc', 'tabc', 'q', 'jabcuabc9']
for i in range(len(lst)):
    dummy_lst = lst[i].split('abc')
    if len(dummy_lst) <= 2:
        lst[i] = ' q '.join(dummy_lst)
    else:
        lst[i] = 'abc'.join(dummy_lst[:-1]) + ' q ' + dummy_lst[-1]
print(lst)

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

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