如何在循环中创建新的嵌套列表?

问题描述 投票:0回答:1

我正在尝试将用户输入中的所有 E 和 B 转换为二进制序列。例如,如果输入是“我是 BBEBE 岁,我的儿子是 BBE”,我想用占位符数字替换该字符串中的 E/B,并将 EB 数字存储在嵌套列表中。 所以我的列表看起来像 EB_to_01 = [[1,1,0,1,0],[1,1,0]] 。

userinput = str(input(''))
    newstring1 = ''
    EB_to_01 = []
    placeholder = 0
    y = 0

    while y < len(userinput) :

        for i in userinput[y:] :
            if i != 'E' and i != 'B' :
                newstring1 += (i)
                y += 1
            else : break

        placeholder += 1
        sub_list = []

        for i in userinput[y:]:
            if i == 'E' :
                newstring1 += str(placeholder)
                sub_list.append(0) # replace 0 with i to add BE_to_01 function
                y += 1
            elif i == 'B' :
                newstring1 += str(placeholder)
                sub_list.append(1) # replace 1 with i to add BE_to_01 function
                y += 1
            else :
                EB_to_01.append(sub_list)
                break

到目前为止,我的代码完全忽略了 EB 的第二个序列,并嵌套了前 5 次。我正在寻找的是 [[1,1,0,1,0],[1,1,0]]

我的整个代码如下所示:

def decode(userinput) :

    userinput = str(input(''))
    newstring1 = ''
    EB_to_01 = []
    placeholder = 0
    y = 0

    while y < len(userinput) :

        for i in userinput[y:] :
            if i != 'E' and i != 'B' :
                newstring1 += (i)
                y += 1
            else : break

        placeholder += 1
        sub_list = []

        for i in userinput[y:]:
            if i == 'E' :
                newstring1 += str(placeholder)
                sub_list.append(0)
                y += 1
            elif i == 'B' :
                newstring1 += str(placeholder)
                sub_list.append(1)
                y += 1
            else :
                EB_to_01.append(sub_list)
                break


    final_output = ''
    a = 1

    for i in newstring1:
        if i.isdigit() :
            b = 1
            for x in EB_to_01 :
                if b == a:
                    u = str(int("".join(str(x) for i in x), 2))
                    final_output += u
                else:
                    b += 1
        else:
            final_output += i
            a += 1
    

    return final_output

print(decode(userinput=str))
python-3.x loops nested-lists
1个回答
0
投票
import re

test_str = "i am BBEBE years old, my son is BBE"

pattern = r'[BE]+'
BEs = re.findall(pattern, test_str)

map_dic = {'B': 1, 'E': 0}

enc_BEs = [[map_dic[char] for char in BE] for BE in BEs]
enc_BEs
© www.soinside.com 2019 - 2024. All rights reserved.