Iterating through nested list - python

How do i create a function to iterate my list in this manner.
Seems simply but im stuck...
myList= [[1,2,3], [4,5,6], [7,8,9]]
def name(myList):
somework..
newList = [[1,4,7]. [ 2,5,8], [3,6,9]]

In [3]: zip(*myList)
Out[3]: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
if you specifically want list
In [4]: [list(x) for x in zip(*myList)]
Out[4]: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
for more details on zip function look at this

zip is what you want + argument unpacking. It's awesome. I like to think of it as python's builtin transpose.
newList = zip(*myList)
This will actually give you an iterable (python3.x) or list (python2.x) of tuple, but that's good enough for most purposes.

Related

How can I turn two lists of equal lengths into a list of nested lists that represent ordered pairs?

For example, if these are my two lists:
a=[1,2,3,4,5]
b=[6,7,8,9,10]
Then what I'm trying to do is to figure out a way to get:
c=[[1,6],[2,7],[3,8],[4,9],[5,10]]
Sorry for the probably basic question. These are numpy arrays if that makes a difference.
If you want a numpy array as a result, you can build it using array.T:
In [15]: a=np.array([1,2,3,4,5])
In [16]: b=np.array([6,7,8,9,10])
In [17]: np.array([a,b]).T
Out[17]:
array([[ 1, 6],
[ 2, 7],
[ 3, 8],
[ 4, 9],
[ 5, 10]])
Reference: What is the equivalent of "zip()" in Python's numpy?
One approach is using list comprehension and zip:
>>> [[i, j] for i, j in zip(a,b)]
[[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]]
I don't use numpy, but maybe by using zip:
>>> a=[1,2,3,4,5]
>>> b=[6,7,8,9,10]
>>> list(zip(a,b))
[(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]
It returns a list of tuples though.
Just use np.transpose:
>>> np.transpose([a, b])
array([[ 1, 6],
[ 2, 7],
[ 3, 8],
[ 4, 9],
[ 5, 10]])
If you want the result as list just call tolist() afterwards:
>>> np.transpose([a, b]).tolist()
[[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]]
d = []
for i in range(0, 5):
d.append([a[i], b[i])
Is a simple way to create a new 2D list with element pairs. Using the zip() function as others have pointed out is also viable.
I'm pretty sure there is an easier or more pythonic way than this.
c = [list(x) for x in zip(a,b)]
This outputs a list of lists, instead of just doing list(zip(a,b) that outputs a list of tuples. This combines list comprehension and zip
Also avoids the tuple unpacking of [[i,j] for i,j in zip(a,b)]
not sure whats more efficient though
zip(*iterables) Make an iterator that aggregates elements from each of the iterables.
https://docs.python.org/3/library/functions.html#zip
There are multiple ways to do this.
a = [1, 2, 3, 4, 5]
b = [6, 7, 8, 9, 10]
If you just need to access the elements and not modify them, you can use the zip function:
zip(a, b)
>[(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]
If you actually need a list of lists, then you can use a list comprehension:
[[a[i], b[i]] for i in range(len(a))]
>[[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]]
And finally, if you need a numpy array as a result, use the Transpose function:
import numpy as np
np.concatenate([[a], [b]]).T
>array([[1, 6],
[2, 7],
[3, 8],
[4, 9],
[5, 10]])
This will give you what you want.
a = [1,2,3,4,5]
b = [6,7,8,9,10]
c = [list(x) for x in zip(a, b)]
with no libraries, you could use:
a = [1,2,3,4,5]
b = [6,7,8,9,10]
c = [[a[i],b[i]] for i in range(len(a))]

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]]?
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]]
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
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))]

How do I transpose a List? [duplicate]

This question already has answers here:
Transpose list of lists
(14 answers)
Closed 8 years ago.
Let's say I have a SINGLE list [[1,2,3],[4,5,6]]
How do I transpose them so they will be: [[1, 4], [2, 5], [3, 6]]?
Do I have to use the zip function? Is the zip function the easiest way?
def m_transpose(m):
trans = zip(m)
return trans
Using zip and *splat is the easiest way in pure Python.
>>> list_ = [[1,2,3],[4,5,6]]
>>> zip(*list_)
[(1, 4), (2, 5), (3, 6)]
Note that you get tuples inside instead of lists. If you need the lists, use map(list, zip(*l)).
If you're open to using numpy instead of a list of lists, then using the .T attribute is even easier:
>>> import numpy as np
>>> a = np.array([[1,2,3],[4,5,6]])
>>> print(*a)
[1 2 3] [4 5 6]
>>> print(*a.T)
[1 4] [2 5] [3 6]
The exact way of use zip() and get what you want is:
>>> l = [[1,2,3],[4,5,6]]
>>> [list(x) for x in zip(*l)]
>>> [[1, 4], [2, 5], [3, 6]]
This code use list keyword for casting the tuples returned by zip into lists.
You can use map with None as the first parameter:
>>> li=[[1,2,3],[4,5,6]]
>>> map(None, *li)
[(1, 4), (2, 5), (3, 6)]
Unlike zip it works on uneven lists:
>>> li=[[1,2,3],[4,5,6,7]]
>>> map(None, *li)
[(1, 4), (2, 5), (3, 6), (None, 7)]
>>> zip(*li)
[(1, 4), (2, 5), (3, 6)]
# ^^ 7 missing...
Then call map again with list as the first parameter if you want the sub elements to be lists instead of tuples:
>>> map(list, map(None, *li))
[[1, 4], [2, 5], [3, 6]]
(Note: the use of map with None to transpose a matrix is not supported in Python 3.x. Use zip_longest from itertools to get the same functionality...)
zip() doesn't seem to do what you wanted, using zip() you get a list of tuples. This should work though:
>>> new_list = []
>>> old_list = [[1,2,3],[4,5,6]]
>>> for index in range(len(old_list[0])):
... new_list.append([old_list[0][index], old_list[1][index]])
...
>>> new_list
[[1, 4], [2, 5], [3, 6]]

Re assign a list efficiently

This is a MWE of the re-arrainging I need to do:
a = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]]
b = [[], [], []]
for item in a:
b[0].append(item[0])
b[1].append(item[1])
b[2].append(item[2])
which makes b lool like this:
b = [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]
I.e., every first item in every list inside a will be stored in the first list in b and the same for lists two and three in b.
I need to apply this to a somewhat big a list, is there a more efficient way to do this?
There is a much better way to transpose your rows and columns:
b = zip(*a)
Demo:
>>> a = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]]
>>> zip(*a)
[(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)]
zip() takes multiple sequences as arguments and pairs up elements from each to form new lists. By passing in a with the * splat argument, we ask Python to expand a into separate arguments to zip().
Note that the output gives you a list of tuples; map elements back to lists as needed:
b = map(list, zip(*a))

How to merge lists into a list of tuples?

What is the Pythonic approach to achieve the following?
# Original lists:
list_a = [1, 2, 3, 4]
list_b = [5, 6, 7, 8]
# List of tuples from 'list_a' and 'list_b':
list_c = [(1,5), (2,6), (3,7), (4,8)]
Each member of list_c is a tuple, whose first member is from list_a and the second is from list_b.
In Python 2:
>>> list_a = [1, 2, 3, 4]
>>> list_b = [5, 6, 7, 8]
>>> zip(list_a, list_b)
[(1, 5), (2, 6), (3, 7), (4, 8)]
In Python 3:
>>> list_a = [1, 2, 3, 4]
>>> list_b = [5, 6, 7, 8]
>>> list(zip(list_a, list_b))
[(1, 5), (2, 6), (3, 7), (4, 8)]
In python 3.0 zip returns a zip object. You can get a list out of it by calling list(zip(a, b)).
You can use map lambda
a = [2,3,4]
b = [5,6,7]
c = map(lambda x,y:(x,y),a,b)
This will also work if there lengths of original lists do not match
Youre looking for the builtin function zip.
I am not sure if this a pythonic way or not but this seems simple if both lists have the same number of elements :
list_a = [1, 2, 3, 4]
list_b = [5, 6, 7, 8]
list_c=[(list_a[i],list_b[i]) for i in range(0,len(list_a))]
The output which you showed in problem statement is not the tuple but list
list_c = [(1,5), (2,6), (3,7), (4,8)]
check for
type(list_c)
considering you want the result as tuple out of list_a and list_b, do
tuple(zip(list_a,list_b))
I know this is an old question and was already answered, but for some reason, I still wanna post this alternative solution. I know it's easy to just find out which built-in function does the "magic" you need, but it doesn't hurt to know you can do it by yourself.
>>> list_1 = ['Ace', 'King']
>>> list_2 = ['Spades', 'Clubs', 'Diamonds']
>>> deck = []
>>> for i in range(max((len(list_1),len(list_2)))):
while True:
try:
card = (list_1[i],list_2[i])
except IndexError:
if len(list_1)>len(list_2):
list_2.append('')
card = (list_1[i],list_2[i])
elif len(list_1)<len(list_2):
list_1.append('')
card = (list_1[i], list_2[i])
continue
deck.append(card)
break
>>>
>>> #and the result should be:
>>> print deck
>>> [('Ace', 'Spades'), ('King', 'Clubs'), ('', 'Diamonds')]
Or map with unpacking:
>>> list(map(lambda *x: x, list_a, list_b))
[(1, 5), (2, 6), (3, 7), (4, 8)]
>>>
One alternative without using zip:
list_c = [(p1, p2) for idx1, p1 in enumerate(list_a) for idx2, p2 in enumerate(list_b) if idx1==idx2]
In case one wants to get not only tuples 1st with 1st, 2nd with 2nd... but all possible combinations of the 2 lists, that would be done with
list_d = [(p1, p2) for p1 in list_a for p2 in list_b]
Like me, if anyone needs to convert it to list of lists (2D lists) instead of list of tuples, then you could do the following:
list(map(list, list(zip(list_a, list_b))))
It should return a 2D List as follows:
[[1, 5],
[2, 6],
[3, 7],
[4, 8]]

Categories

Resources