indices
compare two lists in python and return indices of matched values
The best way to do this would be to make b a set since you are only checking for membership inside it. >>> a = [1, 2, 3, 4, 5] >>> b = set([9, 7, 6, 5, 1, 0]) >>> [i for i, item in enumerate(a) if item in b] [0, 4]
Can someone please explain the “indices trick”?
The problem is: we have a std::tuple<T1, T2, …> and we have some function f that we can to call on each element, where f returns an int, and we want to store those results in an array. Let’s start with a concrete case: template <typename T> int f(T ) { return sizeof(T); } std::tuple<int, … Read more
Get the first column of a matrix represented by a vector of vectors
As I mentioned in the comments, it’s not practical to represent matrices using vector-of-vector for a few reasons: It is fiddly to set up; It is difficult to change; Cache locality is bad. Here is a very simple class I have created that will hold a 2D matrix in a single vector. This is pretty … Read more
Splitting a string by list of indices
s=”long string that I want to split up” indices = [0,5,12,17] parts = [s[i:j] for i,j in zip(indices, indices[1:]+[None])] returns [‘long ‘, ‘string ‘, ‘that ‘, ‘I want to split up’] which you can print using: print ‘\n’.join(parts) Another possibility (without copying indices) would be: s=”long string that I want to split up” indices = … Read more
Is a JavaScript array index a string or an integer?
Formally, all property names are strings. That means that array-like numeric property names really aren’t any different from any other property names. If you check step 6 in the relevant part of the spec, you’ll see that property accessor expressions are always coerced to strings before looking up the property. That process is followed (formally) … Read more
How to get the index of a maximum element in a NumPy array along one axis
>>> a.argmax(axis=0) array([1, 1, 0])
How to number/label data-table by group-number from group_by?
dplyr has a group_indices() function that you can use like this: df %>% mutate(label = group_indices(., u, v)) %>% group_by(label) …
Access lapply index names inside FUN
Unfortunately, lapply only gives you the elements of the vector you pass it. The usual work-around is to pass it the names or indices of the vector instead of the vector itself. But note that you can always pass in extra arguments to the function, so the following works: x <- list(a=11,b=12,c=13) # Changed to … Read more
How to find all occurrences of an element in a list
You can use a list comprehension with enumerate: indices = [i for i, x in enumerate(my_list) if x == “whatever”] The iterator enumerate(my_list) yields pairs (index, item) for each item in the list. Using i, x as loop variable target unpacks these pairs into the index i and the list item x. We filter down … Read more