Python "list out of the range"

Asked

Viewed 243 times

1

I’m trying to put two columns of data, each 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. You can help me?

Usually this error appears when I call a data that is not in a vector or exceeds the size of the vector (???think???) but in this case I am creating a vector and assigning data to it ne. In the case of a matrix. * I’ve tried to do just adding up the values (e.g. a+b) to see if the two were on each other’s side as a concatenation of a text and it didn’t work, so I don’t know anymore. I went to try this matrix and I could not tbm anyway... 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()

3 answers

3


There are some problems in your code:

  1. The function write just wait one string as parameter. If you want to write multiple items at once, use the function writelines, which accepts a list of string as a parameter.

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

    2.1. Use and concatenate before. Decreases code complexity.

Behold:

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 solution more pythonica:

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 the use of with, We don’t have to worry about closing the file. For each one, we read the contents and store the value of each line, excluding the last character, referring to the \n. This is done through a list compression:

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

Finally, write the concatenation of the values in the third file. Concatenation is done through a list compression and function zip, python native.


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
  • Wow, I love you! I understand the code and thank you very much. I will train more. :)

  • Could you help me with the concept of "pythonico" and where I can learn more of these patterns in Python? I’ve heard similar terms a few times.

  • 1

    @Vinicius, the concept "pythonico" consists of writing the code using the tools that Python has and not just applying vices of other languages. The use of for/while is one of the main examples. Anyone who comes from another language to Python has the habit of using them when working with vectors, but almost always there is a simpler way to do it with Python than writing the for/while, such as list compression.

  • Perfect, I’ll read the list documentation. Thanks. :-)

  • 1

    @Vinicius, you can read on PEP8, which defines some style conventions and can search the web for Beautiful python or idiomatic python. That one video by Raymond Hettinger (Python contributor) is a beautiful example.

0

In Python, a list is represented as a sequence of comma-separated objects and within square brackets [], so an empty list, for example, can be represented by square brackets with no content. List 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 printing, which shows only the square brackets, indicating that the list is empty;
  • Lines 4 to 6: Assignment of two strings and two integers to the list variable and its subsequent printing;
  • Lines 7 to 9: Creation and printing of the new_list variable, which is initialized with the string 'stone', and another list.

The possibilities of declaring and assigning values to a list are several, and the option for one or the other will depend on the context and application.

List operators

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

Representação de uma lista e os índices dos elementos

The list represented in this figure is composed of four elements, whose indices vary from zero to three. For example, the first object, at index 0, is the string 'The car'. Keeping this internal organization in mind, we can access each of the elements using the list[index] syntax, as shown in List 2.

See more on this python course.

0

As you yourself stated, d is a list, but Voce never puts anything on it. Even so, inside your loop, Voce tries to access the elements d[i], and so an error occurs.

What you probably want to do is:

d.append([d2,d1])

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

for item in d:
    arquivo3.write(str(item[0]) + str(item[1]))
  • "arquivo3.write" does not receive a list. That’s what my program says. "write() argument must be str, not list"

  • in reality is the opposite, the argument Voce gave is a list, but the correct argument is of type str. I edited the answer to contain this information.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.