Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Convert Generator into List
#1
Hi guys,

I understand that in order to convert a Generator object to a List, it is as simple as casting a list(<Object Generator>). However, this in my code does not work. I have several functions in another module called script_data, and these return an Object Generator, specifically this: <generator object titulo_obras at 0x036533E0>.
These functions should return all a list, but I don't return them with return but with yield, so I understand that I'm forming an iterator.
This is my main code to put the data of the lists in my personal database:

import script_datos
import mysql.connector
import more_itertools


try:
    conn = mysql.connector.connect(host="localhost",port=3306,db="mydb",user="root",password="")
    children_col = script_datos.html_data() #This returns a Generator Object, same as others functions
    col_html = script_datos.html_data_col()
    print("Connection established sucessfully")
    titulos = script_datos.titulo_obras(children_col)
    print(titulos)
    sinopsis = script_datos.sinopsis_obras(children_col)
    tit_org = script_datos.tit_original(children_col)
    dibujantes = script_datos.dibujo_obras(children_col)
    guion = script_datos.guion_obras(children_col)
    ed_franc = script_datos.edicion_francesa(children_col)
    ed_amer = script_datos.edicion_americana(children_col)
    ed_jap = script_datos.edicion_japonesa(children_col)
    ed_esp = script_datos.edicion_española(children_col)
    genero = script_datos.generos_obras(children_col)
    formato = script_datos.formatos_obras(children_col)
    sent_lect = script_datos.sent_lectura_obras(children_col)
    tomos_jap = script_datos.numeros_japon(children_col)
    tomos_esp = script_datos.numeros_españa(children_col)
    cursor = conn.cursor()
    for i in list(titulos):
        print(i)
    cursor.executemany("INSERT INTO `colección`(`Id.coleccion`, `titulo`, `sinopsis`, `titulo_org`, `dibujante`, `guion`, `ed.francesa`, `ed.americana`, `ed.japonesa`, `ed.española`, `genero`, `formato`, `sent.lectura`, `tomos_jap`, `tomos_esp`) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",0, str(titulos[ind]), str(sinopsis[ind]), str(tit_org[ind]), str(dibujantes[ind]), str(guion[ind]), str(ed_franc[ind]), str(ed_amer[ind]), str(ed_jap[ind]), str(ed_esp[ind]), str(genero[ind]), str(formato[ind]), str(sent_lect[ind]), str(tomos_jap[ind]), str(tomos_esp[ind]))
    print("Se han añadido correctamente todas los datos")
    conn.commit()
except mysql.connector.Error as e:
    print("Failed to insert record into MySQL table {}".format(error))
finally:
    if (conn.is_connected()):
        cursor.close()
        conn.close()
        print("MySQL connection is closed")
I need to get the indexes of each of the elements in the lists, however with the Object Generator I don't know how to do that. With the lists it would be as easy as making an .index().
If I try to cast a list, for example:
titulos = list(script_datos.titulo_obras(children_col)).
If I try to print the list or try to browse through it, it doesn't return anything.
Do you know how I can get the indexes from the Generator or how to convert it to list?
Reply
#2
I think the problem is that you are using children_col several times. Look at this example where I define a generator 'spam'
>>> def spam():
...     for x in range(5):
...         yield x**2
... 
>>> s = spam()
>>> s
<generator object spam at 0x7ff9d3628678>
>>> list(s)
[0, 1, 4, 9, 16]
>>> list(s)
[]
The first time I call list(s), it creates the list by traversing the generator s, but then the generator is 'exhausted'. The second time I call list(s), it returns the empty list.

The solution is to convert s to list immediately because a list can be traversed several times
>>> s = list(spam())
>>> list(s)
[0, 1, 4, 9, 16]
>>> list(s)
[0, 1, 4, 9, 16]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  convert string to float in list jacklee26 6 1,913 Feb-13-2023, 01:14 AM
Last Post: jacklee26
  convert a list to links Pir8Radio 3 1,099 Nov-28-2022, 01:52 PM
Last Post: Pir8Radio
  convert this List Comprehensions to loop jacklee26 8 1,512 Oct-21-2022, 04:25 PM
Last Post: deanhystad
  Convert list to interger Clives 5 1,634 May-09-2022, 12:53 PM
Last Post: deanhystad
  Convert each element of a list to a string for processing tester_V 6 5,324 Jun-16-2021, 02:11 AM
Last Post: tester_V
  convert numbers into list lokesh 1 2,382 Jun-03-2021, 06:37 AM
Last Post: menator01
Question convert unlabeled list of tuples to json (string) masterAndreas 4 7,462 Apr-27-2021, 10:35 AM
Last Post: masterAndreas
Star Convert Bytearray into List using list() Shlok 2 4,146 Feb-18-2021, 10:44 AM
Last Post: deanhystad
  convert List with dictionaries to a single dictionary iamaghost 3 2,867 Jan-22-2021, 03:56 PM
Last Post: iamaghost
  What is the difference between a generator and a list comprehension? Pedroski55 2 2,221 Jan-02-2021, 04:24 AM
Last Post: Pedroski55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020