1

I have a list of data called ID, and another list called Dates. They are paired data, and the lists are of equal lengths, approximately 800,000 items long each. I want to pair each item from each list, put them into a tuple, and append these tuples into another list. I.e.:

ID = [1,2,3,4,...]
Dates = [2012-04-05, 2012-04-07, 2012-04-08, 2012-04-09,...]

ID_Datetime = [(1,2012-04-05), (2,2012-04-07), (3,2012-04-08), (4,2012-04-09)...]

Here's my try. It seems like it works, but when I tried to use it on the actual lists, my computer crashed because it couldn't handle the data.

def list_combine():
    for i in ID:
           for j in Dates:
               ID_Datetime.append((i, j))

Any tips on a faster way to do this?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Andrew Louis
  • 303
  • 1
  • 2
  • 15

2 Answers2

2

You are looking for the zip function, which will return (in Python 3) a zip object that you can iterate through:

>>> ID = [1,2,3,4]
>>> DateTime = ['2012-04-05', '2012-04-07', '2012-04-08', '2012-04-09']
>>> zip(ID, DateTime)
<zip object at 0x012EC828>

You can also call list on the object if you want the full list:

>>> list(zip(ID, DateTime))
[(1, '2012-04-05'), (2, '2012-04-07'), (3, '2012-04-08'), (4, '2012-04-09')]
brianpck
  • 8,084
  • 1
  • 22
  • 33
0

Use izip from the itertools module. This creates an iterator from your lists instead of building another one and this way saves memory.


barrios
  • 1,104
  • 1
  • 12
  • 21