如何在迭代包含重复项的列表时使用next()函数(在python 3.7.2中)?

时间:2019-04-01 07:58:25

标签: python loops iterator

我有一个字符串,说p = '25 VHVH 74 V 6 HV 8 VH ”。在这里,VHVH,V,HV,VH称为链。 链1 = VHVH链2 = V链3 = HV链4 = VH。

我想随机选择任意一条链并对其进行补充(意味着将H变为V或将V变为H)。

例如,如果我捡起chain1,那么如果我捡起chain4,则我的字符串将为p = '25 HVHV 74V6HV8VH',那么我的字符串将为p ='25VHVH74V6HV8 HV '

摘要:

输入:“ 25 VHVH 74 V 6 HV 8 VH

输出:'25 HVHV 74V6HV8VH'或'25VHVH74 H 6HV8VH'或'25VHVH74V6 VH 8VH'或'25VHVH74V6HV8 HV ” '

目前,我能够获取每个链开始的索引。然后使用list.index()我应该替换其中之一,但是我认为这不是实现我想要的有效方式。我被这个事实卡住了...

    pe = list(enumerate(polish_exp))
    chain_pos = {}
    for i in pe:
        if i[1] in ['H','h','V','v']:
            chain_pos.update({i[0]:[i[1]]})
            count = 0
            for j in pe[pe.index(i)+1:]:
                if j[1] in ['H','h','V','v']:
                    chain_pos[i[0]].append(j[1])
                    count += 1
                else:
                    break
    print(chain_pos)

我目前正在获取上述代码的输出

{2:['V'],4:['H'],8:['V','H'],9:['H'],11:['V'],13: ['V','H'],14:['H']}

输入:'25VHVH74V6HV8VH'

预期输出:“ 25HVHV74V6HV8VH”或“ 25VHVH74H6HV8VH”或“ 25VHVH74V6VH8VH”或“ 25VHVH74V6HV8HV”

1 个答案:

答案 0 :(得分:0)

最后,我自己找到了解决方案。这就是!!!!!!

def complement_chain(string):
    p = dict(enumerate(string))
    chain_pos = {}
    for i in p.keys():
        if p[i] in ['H','h','V','v']:
            if p[i-1] not in ['H','h','V','v']:
                chain_pos.update({i:[p[i]]})
                for j in list(p.keys())[i+1:]:
                    if p[j] in ['H','h','V','v']:
                        chain_pos[i].append(p[j])
                    else:
                        chain_pos.update({i:''.join(chain_pos[i])})
                        break
    chosen_chain_key = random.choice(list(chain_pos.keys()))
    transtable = str.maketrans('hHvV','vVhH')
    chain_pos.update({chosen_chain_key:chain_pos[chosen_chain_key].translate(transtable)})
    l = chosen_chain_key + len(chain_pos[chosen_chain_key])
    new_string = string[:chosen_chain_key] + chain_pos[chosen_chain_key] + string[l:]
    return new_string

测试输入:2HV1H37HVHV6V8VHV9

输出1:2HV1 V 37HVHV6V8VHV9

输出2:2HV1H37HVHV6V8 HVH 9

输出3:2HV1H37HVHV6 H 8VHV9