Jeremy G
Jeremy G

Reputation: 2409

Python Mapping Arrays

I have one array pat=[1,2,3,4,5,6,7] and a second array count=[5,6,7,8,9,10,11]. Is there a way without using dictionaries to get the following array newarray=[[1,5],[2,6],[3,7],[4,8],[5,9],[6,10],[7,11]]?

Upvotes: 1

Views: 981

Answers (3)

Andrew Winterbotham
Andrew Winterbotham

Reputation: 1010

Without using zip, you can do the following:

def map_lists(l1, l2):
    merged_list = []
    for i in range(len(l1)):
        merged_list.append([l1[i], l2[i]])
    return merged_list

Or, the equivalent, using a list comprehension instead:

def map_lists(l1, l2):
    return [[l1[i], l2[i]] for i in range(len(l1))]

Upvotes: 0

Anand S Kumar
Anand S Kumar

Reputation: 90979

If you want inner elements to be list, you can use -

>>> pat=[1,2,3,4,5,6,7]
>>> count=[5,6,7,8,9,10,11]
>>> newarray = list(map(list,zip(pat,count)))
>>> newarray
[[1, 5], [2, 6], [3, 7], [4, 8], [5, 9], [6, 10], [7, 11]]

This first zips the two lists, combining the ith element of each list, then converts them into lists using map function, and later converts the complete outer map object (that we get from map function) into list

Upvotes: 3

Cory Kramer
Cory Kramer

Reputation: 117951

You can just zip the lists

>>> pat=[1,2,3,4,5,6,7]
>>> count=[5,6,7,8,9,10,11]
>>> list(zip(pat,count))
[(1, 5), (2, 6), (3, 7), (4, 8), (5, 9), (6, 10), (7, 11)]

Or if you want lists instead of tuples

>>> [[i,j] for i,j in zip(pat,count)]
[[1, 5], [2, 6], [3, 7], [4, 8], [5, 9], [6, 10], [7, 11]]

Upvotes: 4

Related Questions