Python itertools; Cyclling through a list

 

If you want to loop through a list in Python, and everytime you hit the last one you loop back and start from the beginning without throwing an exception you can use the Cycle module:


>>> <strong>from itertools import cycle</strong>
>>> my_list = [1,2,3]
>>> <strong>my_cycle = cycle(my_list)</strong>
>>> my_cycle.next()
1
>>> my_cycle.next()
2
>>> my_cycle.next()
3
>>> my_cycle.next()
1
>>> my_cycle.next()
2
>>> my_cycle.next()
3
>>> my_cycle.next()
1

MySQL, Select Random string values from a list of strings

If you have ever wondered how to select a random string value from a list of given string in MySQL the following might be helpful :


UPDATE profile SET `GEO`= ELT(FLOOR(RAND()*8)+1, 
        'US', 'CA', 'FR', 'DE' , 'UK' , 'IR' , 'RU' , 'GR');

The code above sets the GEO field of the profile table to random values selected from a list. That would help when you’re populating dummy information in to your tables for testing.

ELT Command will return the string of a given index, and by doing a FLOOR(RAND()) , you can easily randomize the given index.

Hope it helps.

Determine MySQL Table’s Primary Key Dynamically

You may have been in a situation which you may need to figure out what is the PRIMARY key field of a given table. Or even if it is a compound key what are the columns building the PRIMARY key.
This usually helps a lot when you’re making some generic tools to do some jobs on a given table.

The Script is fairly easy, the following SQL command returns back all the INDEXes of a given Table :

SHOW INDEX FROM `tbl_name`

As you will see in the result, all the indexes are returned including the PRIMARY ones. The only concern is if the PRIMARY KEY is a compound key it has one entry in the list for each column.

Table           Non_unique  Key_name      Seq_in_index  Column_name 
---------------------------------------------------------------------
test_table      0           PRIMARY       1             Config_ID   
test_table      0           PRIMARY       2             User_ID     
test_table      1           idxSettingID  1             User_ID

So you can easily loop through the results and find the compound keys.

Here is a sample Python script which does the same thing, using the  List Comprehension :

if cursor.execute('SHOW INDEX FROM `test_table`') :
    return  [row[4] for row in cursor.fetchall() if row[2].upper() == 'PRIMARY']
return []

Update – 18.Oct.2011 :

Also you can use the following SQL to get information about the table and loop through it in Python :


DESCRIBE `tbl_name`