如何将字符添加到列表中的元素并输出它?

2024-09-30 02:17:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直试图添加一个字符到一个列表中的元素,但它不工作。你知道吗

我尝试了以下代码行:

listofobjects[i].append(char)

以及

listofobjects[i] = list[i] + char

以及

listofobjects[i] = str(list[i]) + char

在本规范中:

file_enter = open("LogoRLE.txt","r")
#reads line
l = file_enter.readline()
#string where compressed data is stored
compdata = ''
#string where uncompressed data will be stored
uncompdata = ''
#count is used so decompression can stop once the file has been read
count = 0
#counts for every three characters
charcount = 0
#listno is used to add decompressed characters to a specific element
listno = 0
#where all uncompressed data will stored
uncompdatal = []

while charcount != len(file_enter.read()):

    for i in str(l):
        count += 1

        charcount += 1

        compdata = compdata + i
        print (compdata)

        if count == 3:

            number = int(compdata[:2])

            char = compdata[2:]

            compdata = char*number

            uncompdata = uncompdata + compdata

            uncompdatal.append(uncompdata)

            uncompdatal[listno] = str(uncompdatal[listno]) + uncompdata

            print(uncompdatal)
            #resets values for next three characters

            compdata = ''

            uncompdata = ''

            count = 0

            print(charcount)

            #display(uncompdatal)


    l = file_enter.readline()
    print(l)

    listno += 1

我在读文本文件中的字符。我读了一行,将它存储为一个字符串,并将每3个字符分开,因为它是RLE压缩的,我正在尝试解压缩。你知道吗

3个字符的示例:

01f04g02,

在解压了行的前三个字符之后,我将其附加到一个列表中,并希望将其他解压字符添加到一个元素中,用于一个解压行。你知道吗

我希望它输出这个结果:

["fgggg,,"]

它不工作,因为有一个输出,但它是不可能看到它,因为shell一直在运行,什么也没有显示。你知道吗


Tags: datacountwhere字符fileprintentercharcount
2条回答

可以使用字符串连接

>>> words = ['foo', 'bar']
>>> words[1] += 's'
>>> words
['foo', 'bars']

您使用的第二个选项应该可以正常工作:

>>> list = ['a', 'b', 'c']
>>> list[0] = list[0] + 'z'
>>> print(list)
['az', 'b', 'c']

你能把使用第二个选项时遇到的错误公布出来吗?你知道吗

相关问题 更多 >

    热门问题