Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combine multiple lists horizontally into a single list

Tags:

python

list

I have searched up and down for this in python and could not find exactly what I'm looking for.

Suppose I have the following example:

date_list = [Mar 27 2015, Mar 26 2015, Mar 25 2015]
num_list_1 = [22, 35, 7]
num_list_2 = [15, 12, 2]

How do I combine the lists so my end result is something like this:

combined_list = [Mar 27 2015, 22, 15
                 Mar 26 2015, 35, 12
                 Mar 25 2015, 7, 2]

Once I have the data in the combined_list variable, I want to be able to pass it to a for loop and iterate over each line and insert it into my SQLite db if the date does not exist or update the existing record if the date is found.

I have my separate lists and I have the database insert working. What I'm not sure about is the proper way to combine the lists. Am I looking for a pandas dataframe? Or something else?

Any pointers to nudge me in the right direction would be appreciated

like image 201
ChrisC Avatar asked Nov 15 '25 21:11

ChrisC


1 Answers

Use zip on the three lists (I've corrected the date_list's format, the Original post doesn't have it in correct strings):

>>> date_list = ["Mar 27 2015", "Mar 26 2015", "Mar 25 2015"]
>>> num_list_1 = [22, 35, 7]
>>> num_list_2 = [15, 12, 2]
>>> list(zip(date_list, num_list_1, num_list_2))
[('Mar 27 2015', 22, 15), ('Mar 26 2015', 35, 12), ('Mar 25 2015', 7, 2)]

And as a single list using a simple list comprehension in conjunction with zip:

>>> [item for items in zip(date_list, num_list_1, num_list_2) for item in items]
['Mar 27 2015', 22, 15, 'Mar 26 2015', 35, 12, 'Mar 25 2015', 7, 2]

Note: This answer is not pandas dependent, if you are looking for a way to do this in pandas, check @EdChum's answer.

like image 142
Anshul Goyal Avatar answered Nov 17 '25 10:11

Anshul Goyal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!