Combines lists by rows (Python)

Say I have 3 different lists

col1 = ['2006-03-28','2006-04-05','2006-04-06'] col2 = ['IBM', 'MSFT', 'IBM'] col3 = [1000, 1000, 500] 

What is the most efficient way to combine these lists into another list:

 col = [('2006-03-28', 'IBM', 1000), ('2006-04-05', 'MSFT', 1000), ('2006-04-06', 'IBM', 500)] 
+4
source share
2 answers
 >>> col1 = ['2006-03-28','2006-04-05','2006-04-06'] >>> col2 = ['IBM', 'MSFT', 'IBM'] >>> col3 = [1000, 1000, 500] >>> zip(col1, col2, col3) [('2006-03-28', 'IBM', 1000), ('2006-04-05', 'MSFT', 1000), ('2006-04-06', 'IBM', 500)] 

If your columns are already on the same list, you can simply use zip(*cols)

+12
source

The code is as follows: Python 3.x

 >>> col1 = ['2006-03-28','2006-04-05','2006-04-06'] >>> col2 = ['IBM', 'MSFT', 'IBM'] >>> col3 = [1000, 1000, 500] >>> col = list(zip(col1 ,col2 ,col3 )) >>> print(str(col)) [('2006-03-28', 'IBM', 1000), ('2006-04-05', 'MSFT', 1000), ('2006-04-06', 'IBM', 500)] 

Just the zip () syntax, which it itself works for Python 2.x. Use the above code to combine lists as rows (or columns of an expanded sheet) in Python 3.x.

0
source

All Articles