How to Get the Index of an Item in a List in a Single Step

How can I get the index of an item in a list in a single step?

How about the List.FindIndex Method:

int index = myList.FindIndex(a => a.Prop == oProp);

This method performs a linear search; therefore, this method is an
O(n) operation, where n is Count.

If the item is not found, it will return -1

How to get index from Liststring of specific item?

You don't need LINQ for that. List has an FindIndex method. It takes a predicate and returns the index of the first element that matches. In the predicate you can compare the strings using String.Equals and use a StringComparison parameter to ignore the case.

private int getColorIndex(string colorName , List<string> headers)
{
int index = headers.FindIndex(s => String.Equals(s, colorName, StringComparison.InvariantCultureIgnoreCase));
}

Find the index of an item in a list of lists

I'd do something like this:

[(i, colour.index(c))
for i, colour in enumerate(colours)
if c in colour]

This will return a list of tuples where the first index is the position in the first list and second index the position in the second list (note: c is the colour you're looking for, that is, "#660000").

For the example in the question, the returned value is:

[(0, 0)]

If you just need to find the first position in which the colour is found in a lazy way you can use this:

next(((i, colour.index(c))
for i, colour in enumerate(colours)
if c in colour),
None)

This will return the tuple for the first element found or None if no element is found (you can also remove the None argument above in it will raise a StopIteration exception if no element is found).

Edit: As @RikPoggi correctly points out, if the number of matches is high, this will introduce some overhead because colour is iterated twice to find c. I assumed this to be reasonable for a low number of matches and to have an answer into a single expression. However, to avoid this, you can also define a method using the same idea as follows:

def find(c):
for i, colour in enumerate(colours):
try:
j = colour.index(c)
except ValueError:
continue
yield i, j

matches = [match for match in find('#660000')]

Note that since find is a generator you can actually use it as in the example above with next to stop at the first match and skip looking further.

Fastest way to find Indexes of item in list?

def find(target, myList):
for i in range(len(myList)):
if myList[i] == target:
yield i

def find_with_list(myList, target):
inds = []
for i in range(len(myList)):
if myList[i] == target:
inds += i,
return inds

In [8]: x = range(50)*200
In [9]: %timeit [i for i,j in enumerate(x) if j == 3]
1000 loops, best of 3: 598 us per loop

In [10]: %timeit list(find(3,x))
1000 loops, best of 3: 607 us per loop
In [11]: %timeit find(3,x)
1000000 loops, best of 3: 375 ns per loop

In [55]: %timeit find_with_list(x,3)
1000 loops, best of 3: 618 us per loop

Assuming you want a list as your output:

  • All options seemed exhibit similar time performance for my test with the list comprehension being the fastest (barely).

If using a generator is acceptable, it's way faster than the other approaches. Though it doesn't account for actually iterating over the indices, nor does it store them, so the indices cannot be iterated over a second time.

How to find index of an item in a List where two or more property need to be check

All you need to do is:

int index = myList.FindIndex(a => a.Prop1 == oProp1 && a.Prop2 == oProp2);

Get index value of list on condition in C#

If you need to get the index of an existing string that you know completely use:

int index = list.IndexOf("user");

If the string only contains "user" but may be a bigger string that you don't have:

int index = list.FindIndex(item => item.Contains("user"));

In both cases, if index is 0 or greater you have the index and a negative value signals that the item was not found.

Get the element of list or index of list while for looping with step in range

The logic isn't identical to your version, but maybe you want to achieve something similar to this?

for i, name in enumerate(list_of_names):
print(i * 7 + 1, (i + 1) * 7, name)

In your version, as list_of_names grows, the number of elements that aren't printed will increase by one at each list length n*6 + 1, n being a positive integer. For instance, when the length is 7, only the first 6 items will be printed (i.e., i taking on values [1, 8, 15, 22, 29, 36], but not 43) and by length 13, only 11 elements would be printed.

If possible, you should be using Python 3 instead. Python 2 is no longer maintained.

Finding index of an item in C#List

You can use the indexOf method on List<T> to find the index of the first matching item:

var items = new List<string> { "Joseph", "Mary", "John", "Peter", "Andrew" };

var indexOfMary = items.IndexOf("Mary");

var itemAtIndexOfMary = items[indexOfMary];

Once you've done that you can then index into the list (the last line of code) at any point to retrieve the item at that position.

How to find index of an element in Python list?

Actually you don't have to operate with indexes here. Just iterate over words list and check if the word is listed in nasty. If it is append 'CENSORED' to the result list, else append the word itself.

Or you can involve list comprehension and conditional expression to get more elegant version:

Return the index of the first element in the list from where incremental increase starts

Solution 1: operator

from operator import sub, indexOf

L = [ 0, 4, 6, 8, 12, 15, 19, 21, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32]

print(indexOf(map(sub, L[1:], L), 1))
# prints 8

Raises ValueError: sequence.index(x): x not in sequence if difference 1 never occurs, so might want to use try/except for that.

Solution 2: bisect

This one only takes O(log n) time, using the monotonicity of incrementalness (as you commented "once the increase becomes incremental it will continue to stay that way").

from bisect import bisect

L = [ 0, 4, 6, 8, 12, 15, 19, 21, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32]

class IsIncremental:
def __getitem__(_, i):
return L[i+1] - L[i] == 1

print(bisect(IsIncremental(), False, 0, len(L) - 1))
# prints 8

Prints len(L) - 1 if difference 1 never occurs.

Btw... readability

As PEP 8 says:

Never use the characters 'l' (lowercase letter el), [...] as single character variable names. In some fonts, these characters are indistinguishable from the numerals one and zero. When tempted to use 'l', use 'L' instead.



Related Topics



Leave a reply



Submit