Python "list out of the range"

0

I'm trying to put two columns of data, each one in a different file with the names you'll see in the code, in a single file as two columns side by side. The error, quoted in the title ("list out of the range") always appears where I will indicate with an asterisk in the code. Can you help me?

Normally this error appears when I call a data that is not in a vector or exceeds the size of the vector (??? I think ???) but in the case I am creating a vector and assigning data to it ne. In the case a same matrix. * I already tried to do so by adding the values (ex a + b) to see if the two were next to each other as a concatenation of a text and did not work, then I do not know anymore. I went to try this matrix and I could not finally ... help me!

arquivo1 = open ("bandaIZ_coluna5_dados_não_saturados.txt","r")
dados1 = arquivo1.readlines()
arquivo1.close()
arquivo2 = open ("bandaIZ_coluna13_dados_não_saturados.txt","r")
dados2 = arquivo2.readlines()
arquivo2.close()
arquivo3 = open ("bandaIZ_colunas13&5","w")
if(len(dados1) == len(dados2)):
    print("len(dados1) == len(dados2)")
i = 0
d = []
while(i < len(dados1)):
    d2 = (dados2[i])
    d1 = (dados1[i])
    d[i][0] = d2
    d[i][1] = d1  
    i=i+1
arquivo3.write(d)
arquivo3.close()
    
asked by anonymous 17.03.2017 / 02:27

3 answers

3

There are some problems with your code:

  • The function write expects only string as a parameter. If you want to write multiple items at once, use the writelines function, which accepts a list of string as a parameter.

  • You are trying to assign a value to a non-existent position in the list ( d[i][0] = d2 ). As commented in the other answer , you can use append .

    2.1. Enjoy and do the concatenation before. It reduces the complexity of the code.

  • See:

    i = 0
    d = []
    
    while(i < len(dados1)):
        # O [:-1] retira o \n do final
        d2 = dados2[i][:-1]
        d1 = dados1[i][:-1]
        d.append("{} {}\n".format(d2, d1))
        i=i+1
    
    arquivo3.writelines(d)
    

    If you prefer a more pythonic solution:

    with open("bandaIZ_coluna5_dados_não_saturados.txt", "r") as file:
        dados1 = [i[:-1] for i in file.readlines()]
    
    with open("bandaIZ_coluna13_dados_não_saturados.txt", "r") as file:
        dados2 = [i[:-1] for i in file.readlines()]
    
    # Nome do arquivo está estranho
    with open("bandaIZ_colunas13&5", "w") as file:
        file.writelines(["{} {}\n".format(a, b) for a, b in zip(dados2, dados1)])
    

    With with , we do not have to worry about closing the file. For each one, we read the content and store the value of each line, excluding the last character, referring to \n . This is done through a list compression:

    dados = [i[:-1] for i in file.readlines()]
    

    At the end, write the concatenation of the values in the third file. The concatenation is done through list compression and the zip function, native to Python .

    If the input files are:

    File 1

    a
    b
    c
    d
    

    File 2

    e
    f
    g
    h
    

    The final file will be:

    e a
    f b
    g c
    h d
    
        
    17.03.2017 / 03:01
    0

    As you yourself have stated, d is a list, but you never put anything in it. However, within your loop, you try to access the elements d [i], so an error occurs.

    What you probably want to do is:

    d.append([d2,d1])
    

    In addition, the write argument is str, not list. To put the contents of your list on file, you will probably want to do:

    for item in d:
        arquivo3.write(str(item[0]) + str(item[1]))
    
        
    17.03.2017 / 02:37
    0

    In Python, a list is represented as a sequence of objects separated by commas and inside brackets [], so an empty list, for example, can be represented by brackets with no content. Listing 1 shows some possibilities for creating this type of object.

    >>> lista = [] 
    >>> lista
    []
    >>> lista = ['O carro','peixe',123,111]
    >>> lista
    ['O carro', 'peixe', 123, 111]
    >>> nova_lista = ['pedra',lista]
    >>> nova_lista
    ['pedra', ['O carro', 'peixe', 123, 111]]
    
    • Lines 1 to 3: Declaration of a list with no element and its impression, which shows only the brackets, indicating that the list is empty;
    • Lines 4 to 6: Assigning two strings and two integers to the list variable and its subsequent printing;
    • Lines 7 to 9: Creating and printing the variable new_list, which is initialized with the string 'stone', and another list.

    The possibilities of declaring and assigning values to a list are many, and the choice of one or the other depends on the context and application.

    List Operators

    The Python language has several methods and operators to assist in the manipulation of lists. The first and most basic is the operator accessing your items from the indexes. To understand it, it is important to understand how the data is stored in this structure, which is illustrated in Figure 1.

    Thelistrepresentedinthisfigureiscomposedoffourelementswhoseindicesvaryfromzerotothree.Forexample,thefirstobject,atindex0,isthestring'Thecar'.Keepinginmindthisinternalorganization,wecanaccesseachelementusingthesyntaxlist[index],asshowninListing2.

    Seemoreinthis python course .

        
    07.02.2018 / 16:12