Reputation: 179
So I have this list:
Comps = [
[1000, 500, 200, 100, 700, 350, 120, 900, 800],
[1001, 501, 201, 101, 701, 351, 121, 901, 801]
]
How would I get the results [500, 350, 120] and [501, 351, 121] from this list?
I know how to get the answer [500, 350, 120]
if there was only the first list (which would be [1000, 500, 200, 100, 700, 350, 120, 900, 800]
) in the variable Comps. However, I am not sure how to work with a list that contains 2 or more lists (also known as "list of list"). I keep getting the error: "IndexError: list index out of range".
What I've done is this:
print(list(Comps[i] for i in [1, 5, 6]))
Here is the full error for those who are interested:
Traceback (most recent call last):
File "<pyshell#74>", line 1, in <module>
print(list(Comps[i] for i in [1, 5, 6]))
File "<pyshell#74>", line 1, in <genexpr>
print(list(Comps[i] for i in [1, 5, 6]))
IndexError: list index out of range
Upvotes: 1
Views: 157
Reputation: 54223
The reason you get a IndexError: list index out of range
is that Comp
is a list with only 2 elements. Element at index 1
is the second list ([1001, 501, 201, 101, 701, 351, 121, 901, 801]
) but there's no element at index 5
in Comps
.
You could use a nested list comprehension:
>>> Comps = [[1000, 500, 200, 100, 700, 350, 120, 900, 800], [1001, 501, 201, 101, 701, 351, 121, 901, 801]]
>>> [[l[i] for i in [1, 5, 6]] for l in Comps]
[[500, 350, 120], [501, 351, 121]]
If you want them in a flat list:
>>> [l[i] for l in Comps for i in [1, 5, 6]]
[500, 350, 120, 501, 351, 121]
If you work with matrices and arrays, you might want to take a look at numpy:
import numpy as np
comps = np.array([[1000, 500, 200, 100, 700, 350, 120, 900, 800], [1001, 501, 201, 101, 701, 351, 121, 901, 801]])
comps[:,[1, 5, 6]]
# array([[500, 350, 120],
# [501, 351, 121]])
If you only want one of them:
>>> [Comps[0][i] for i in [1, 5, 6]]
[500, 350, 120]
>>> [Comps[1][i] for i in [1, 5, 6]]
[501, 351, 121]
And with NumPy:
>>> comps[0, [1, 5, 6]]
array([500, 350, 120])
>>> comps[1, [1, 5, 6]]
array([501, 351, 121])
Upvotes: 3
Reputation: 812
As there is one list like:
1) math=[one, list]
you always use mathList = math[theIndexOfItemInList]
but as there is two or more you need to change how you count lists, like if there is a list:
2) math=[[one, list], [second, list], [third, list], [etc, list]]
as you call this list:
3) mathList = math[whichListYouNeed][theIndexOfItemInList]
Upvotes: 1
Reputation: 95948
You are almost there, you just need to nest one level deeper:
[[sub[i] for i in [1, 5, 6]] for sub in Comps]
Alternatively, you can use operator.itemgetter
:
>>> list(map(operator.itemgetter(*[1, 5, 6]), Comps))
[(500, 350, 120), (501, 351, 121)]
Or, more directly,
>>> list(map(operator.itemgetter(1, 5, 6), Comps))
[(500, 350, 120), (501, 351, 121)]
Upvotes: 1