python: find the indeces of nested list by condition - python

To get the list indeces that satifies a condition, say None I can do:
[x for (x, e) in enumerate(my_list) if e is None]
But I can not get my head around what to do with a nested list using the same scheme as above. For instance how to find the indeces of my_nlist where the first element in the nested (inner) lists are None.
my_nlist = [[None, 2], [13, 2], [None, 1]]
The expected result would be:
[0,2]

Same as the previous one just use a tuple as the items throwaway variable:
In [5]: [ind for ind, (i, j) in enumerate(my_nlist) if i is None]
Out[5]: [0, 2]

An approach with numpy (maybe clearer than base python but needs a library):
import numpy as np
np.where([None in i for i in L])
#(array([0, 2], dtype=int64),)

Related

Get choose specific elements from an array based on list of index

A=np.array([ [7,8],[7,9],[3,4],[5,4],[3,4],[5,6] ])
indicesB=np.array([ [1] ,[1] ,[1] ,[2] ,[1] ,[2] ])
how can i get all the elements in A if the same position elements in indices B= 1?
for example,
if i want indicesB= 2,then i get[5,4],[5,6]
if i want indicesB= 1,then i get[7,8],[7,9],[3,4],[3,4]
What I want is something like this
Y=np.array([[7,8],[3,4],[3,4],[3,4],[3,4],[3,4]])
X=np.array([[1],[1],[1],[1],[1],[2]])
for x in range(1,3):
for i in range(6):
if X[i]==x:
print('the indice is ', x,Y[i])
how cccan i make it simple using numpy?
If I understand right this code might helps you:
new_list = []
for i,j in zip(A, indicesB):
el = i[:j[0]].tolist()
new_list.append(el)
If you need an array instead of list you should use i[:j[0]] without .tolist() and after loop change type new_list to array like that:
new_list = np.array(new_list)
Can you use dict ? that way you can call perticular key dict[1] and you will receive np.array.
import numpy as np
dic = {s:[] for s in set(np.concatenate([x.ravel() for x in X]))}
[dic[j.tolist()[0]].append(i.tolist()) for i,j in zip(A, B)]
np.array(dic[2]) #or np.array(dic[int(input())])
Output:
array([[5, 4],
[5, 6]])

Iterate Python List of Lists and Remove Final Index of Each Sublist, No Imports

There are a few similar questions to this one but not exactly the same:
I want to dynamically decrease a given input array or list of lists. For example:
matrix = [[0,1,2], [3,4,5],[6,7,8]]
Starting at 0 I need to iterate through and remove the final index - the iterative. So the output I would like to store in a new list is:
#output
[0,1,2], ,[3,4], [6]]
[0,1,2], ,[3,4], [6]] ==> which then flattens to [0,1,2,3,4,6]
Here's what I'm currently going after:
def get_list(matrix, stop_index):
temp = []
for i in range(0, stop_index):
for m in matrix:
temp.append(matrix[0:stop_index])
outside_list.append(temp)
return outside_list
I believe I am seeing well my over reliance on packages and libraries, so I am really trying to do this without outside packages or imports
Thank you for any help! I don't forget to green check mark.
Using list comprehension
l = [[0,1,2], [3,4,5],[6,7,8]]
ll = [ x[:len(l)-l.index(x)] for x in l]
# [[0, 1, 2], [3, 4], [6]]
print([x for y in ll for x in y ])
# [0, 1, 2, 3, 4, 6]
Simpler syntax:
matrix = [[0,1,2], [3,4,5],[6,7,8]]
outside_list = list()
for i in range(len(matrix)):
# matrix[i] is used to access very sublist in the matrix,
#[:3-i] is to slice every sublist from the beginning to (3 - current position)
outside_list.append(matrix[i][:3-i])
print(outside_list)
Some useful refernces
List slicing https://stackoverflow.com/a/509295/8692977
List comprehension: https://stackoverflow.com/a/34835952/8692977

Get all the rows with same values in python?

So, suppose I have this 2D array in python
a = [[1,2]
[2,3]
[3,2]
[1,3]]
How do get all array entries with the same row value and store them in a new matrix.
For example, I will have
b = [1,2]
[1,3]
after the query.
My approach is b = [a[i] for i in a if a[i][0] == 1][0]]
but it didn't seem to work?
I am new to Python and the whole index slicing thing is kind confusing. Thanks!
Since you tagged numpy, you can perform this task with NumPy arrays. First define your array:
a = np.array([[1, 2],
[2, 3],
[3, 2],
[1, 3]])
For all unique values in the first column, you can use a dictionary comprehension. This is useful to avoid duplicating operations.
d = {i: a[a[:, 0] == i] for i in np.unique(a[:, 0])}
{1: array([[1, 2],
[1, 3]]),
2: array([[2, 3]]),
3: array([[3, 2]])}
Then access your array where first column is equal to 1 via d[1].
For a single query, you can simply use a[a[:, 0] == 1].
The for i in a syntax gives you the actual items in the list..so for example:
list_of_strs = ['first', 'second', 'third']
first_letters = [s[0] for s in list_of_strs]
# first_letters == ['f', 's', 't']
What you are actually doing with b = [a[i] for i in a if a[i][0]==1] is trying to index an element of a with each of the elements of a. But since each element of a is itself a list, this won't work (you can't index lists with other lists)
Something like this should work:
b = [row for row in a if row[0] == 1]
Bonus points if you write it as a function so that you can pick which thing you want to filter on.
If you're working with arrays a lot, you might also check out the numpy library. With numpy, you can do stuff like this.
import numpy as np
a = np.array([[1,2], [2,3], [3,2], [1,3]])
b = a[a[:,0] == 1]
The last line is basically indexing the original array a with a boolean array defined inside the first set of square brackets. It's very flexible, so you could also modify this to filter on the second element, filter on other conditions (like > some_number), etc. etc.

How to subtract the value from the previous value in a list in python?

I am trying to take values in a list, such as [1,2,3] and subtract them from each other. So it would return [-1,-1] because the first value is 1-2 and the second value is 2-3. How would i achieve this in python? I have tried
[x-y for (x,y) in list]
but this gives a 'need more than one value to unpack error.'
It's not a good idea to shadow the builtin list, so I changed your variable name here
[x - y for x, y in zip(the_list, the_list[1:])]
If you are able to use numpy.diff, this is quite easy:
In [22]: import numpy as np
In [23]: -np.diff([1,2,3])
Out[23]: array([-1, -1])
In [24]: -np.diff([1,2,4,3])
Out[24]: array([-1, -2, 1])
You can also use a generator created by izipping the list with itself, offset by one index.
from itertools import izip, islice
[x - y for x,y in izip(lst, islice(lst, 1, None))]
This is handy if for some reason lst was itself a generator, or otherwise was not easily examined for its length ahead of time, or you just didn't want to consume it directly.
You can use a list comprehension, but specify a range starting at 1 to the end of the list (or alternatively starting at zero to one minus the length of the list):
lst = [1, 2, 3]
>>> [lst[i - 1] - lst[i] for i in range(1, len(lst))]
[-1, -1]

Indexing a nested list in python

Given data as
data = [ [0, 1], [2,3] ]
I want to index all first elements in the lists inside the list of lists. i.e. I need to index 0 and 2.
I have tried
print data[:][0]
but it output the complete first list .i.e.
[0,1]
Even
print data[0][:]
produces the same result.
My question is specifically how to accomplish what I have mentioned. And more generally, how is python handling double/nested lists?
Using list comprehension:
>>> data = [[0, 1], [2,3]]
>>> [lst[0] for lst in data]
[0, 2]
>>> [first for first, second in data]
[0, 2]
Using map:
>>> map(lambda lst: lst[0], data)
[0, 2]
Using map with operator.itemgetter:
>>> import operator
>>> map(operator.itemgetter(0), data)
[0, 2]
Using zip:
>>> zip(*data)[0]
(0, 2)
With this sort of thing, I generally recommend numpy:
>>> data = np.array([ [0, 1], [2,3] ])
>>> data[:,0]
array([0, 2])
As far as how python is handling it in your case:
data[:][0]
Makes a copy of the entire list and then takes the first element (which is the first sublist).
data[0][:]
takes the first sublist and then copies it.
The list indexing or nesting in general (be it dict, list or any other iterable) works Left to Right. Thus,
data[:][0]
would work out as
(data[:]) [0] == ([[0, 1], [2,3]]) [0]
which ultimately gives you
[0, 1]
As for possible workaronds or proper methods, falsetru & mgilson have done a good job in that regards.
try this:
print [x for x, y in data[:]]

Categories