logo
down
shadow

Finding index of a list containing an item, also in a list


Finding index of a list containing an item, also in a list

By : user2956650
Date : November 22 2020, 10:56 AM
I think the issue was by ths following , Let's say my list is this: , You can use enumerate and list comprehension :
code :
>>> Inventory = [["Item","Quantity"],["Credits","5000"],["Item 1", 2],["Item 3",1]]
>>> [i for i,j in enumerate(Inventory) if j[0]=='Credits']
[1]


Share : facebook icon twitter icon
Finding the index of an item given a list containing it in Python

Finding the index of an item given a list containing it in Python


By : First2Drown
Date : March 29 2020, 07:55 AM
should help you out Given a list ["foo", "bar", "baz"] and an item in the list "bar", how do I get its index (1) in Python?
code :
>>> ["foo", "bar", "baz"].index("bar")
1
list.index(x[, start[, end]])
>>> import timeit
>>> timeit.timeit('l.index(999_999)', setup='l = list(range(0, 1_000_000))', number=1000)
9.356267921015387
>>> timeit.timeit('l.index(999_999, 999_990, 1_000_000)', setup='l = list(range(0, 1_000_000))', number=1000)
0.0004404920036904514
>>> [1, 1].index(1)
0
>>> [i for i, e in enumerate([1, 2, 1]) if e == 1]
[0, 2]
>>> g = (i for i, e in enumerate([1, 2, 1]) if e == 1)
>>> next(g)
0
>>> next(g)
2
>>> [1, 1].index(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 2 is not in list
Most efficient way of finding an item at a certain index in a List<>, modifying the item and then updating the Lis

Most efficient way of finding an item at a certain index in a List<>, modifying the item and then updating the Lis


By : Tere
Date : March 29 2020, 07:55 AM
will be helpful for those in need Well first off you don't need your test for car.RegNumber == 5 in the loop - you've already found the first car that match this criterion from your statement:
code :
Car car = CarsForSale.Find(c => c.RegNumber == 5);
if (car != null)
{
    car.Color = "Red";
}
else
{
    CarsForSale.Add(new Car(5, "Red"));
}
var cars = CarsForSale.Where(c => c.RegNumber == 5);

foreach (Car car in cars)
{
    car.Color = "Red";
}

if (!car.Any())
{
    CarsForSale.Add(new Car(5, "Red"));
}
finding a list item by its index

finding a list item by its index


By : puja
Date : March 29 2020, 07:55 AM
hope this fix your issue I've started off with this.
code :
def month(n):
 lst = ['Months','Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
 return lst[n]
Finding index of an item in C#List

Finding index of an item in C#List


By : Malin Morgan
Date : March 29 2020, 07:55 AM
seems to work fine You can use the indexOf method on List to find the index of the first matching item:
code :
var items = new List<string> { "Joseph", "Mary", "John", "Peter", "Andrew" };

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

var itemAtIndexOfMary = items[indexOfMary];
Finding the index of the first occurrence of any item in a list

Finding the index of the first occurrence of any item in a list


By : Mahmoud Emad
Date : March 29 2020, 07:55 AM
To fix the issue you can do For the list shown in the example: , Turn the list to a set then use .index:
code :
output = [my_list.index(elem) for elem in set(my_list)]
output = sorted(my_list.index(elem) for elem in set(my_list))
>>> my_list = ['hi', 'babe', 'hi', 'babe', 'key', 'key']         
>>> output = sorted(my_list.index(elem) for elem in set(my_list))
>>> output                                                       
[0, 1, 4]   
Related Posts Related Posts :
  • Read data with NAs into python and calculate mean row-wise
  • How to print telnet response line by line?
  • Pylint: Avoid checking INSIDE DOCSTRINGS (global directive / rcfile)
  • Sending MIDI messages using Python (on Ubuntu)
  • Generate Dictionary in Python at run time
  • code is cluttered by try-except in Python
  • Python class inheritance - spooky action
  • Why is a Python multiprocessing daemon process not printing to standard output?
  • How to feed numeric data into a classifier?
  • How to unambiguously identify a Model as a lowercase string in Django
  • How to get only one specific line from subprocess output
  • Python network communication with encryption and password protection
  • with urllib urlopen read function but get none
  • django could not find database in ubuntu
  • How to replace a character in a string with a non ascii character in python?
  • Self learning data evaluation in Python
  • Django: UnicodeDecodeError while trying to read template 500.html
  • how can you Import an os variable into PYTHON and have it update?
  • Browse Folders to open a file in python
  • sql select group by a having count(1) > 1 equivalent in python pandas?
  • Why Insert command when button clicked OpenERP
  • Pandas dataframe from nested dictionary to melted data frame
  • Which is more efficient in Python: list.index() or dict.get()
  • Xor bits in python
  • A simple python confusion about format string
  • How to test Domain is it 'www' domain or subdomain or name server domain or mail domain in python?
  • Keydown event for Pygame
  • Lazy loading csv with pandas
  • Use webdriver,python,beautifulsoup to retrieve dynamic website
  • Scrapy is Visiting same Url despite dont_filter=False
  • How to add support for SNI in python 2.7
  • Pandas: np.where with multiple conditions on dataframes
  • How to get meaningful words by splitting a continuous string?
  • TypeError: 'numpy.ndarray' object is not callable while extracting index and elements are stored in different array in p
  • Python: comparing list to a string
  • Is there any way to write '\r' into a file on linux with python?
  • matplotlib retrieve color from plt.plot command
  • Scrapy JSON export issues
  • beautifulsoup to retrieve the date
  • Django Rest Framework 3.0: Saving Nested, Many-To-One Relationship
  • Lost connection to MySQL server during Python connection
  • uploadede file path django
  • How to reduce a data with the longest string under pandas framework?
  • Single line for-loop to build a dictionary?
  • How to read in lines until a certain line?
  • Beautifulsoup to retrieve the href list
  • Python - Vincenty's inverse formula not converging (Finding distance between points on Earth)
  • Saving django model instance into another model
  • Same URL request fails with python->urllib but not with curl
  • Python dictionary: set value as the key string
  • With setuptools, when does namespace packages __init__.py files disappears?
  • Paraview: NameError: name 'inputs' is not defined
  • Too many values to unpack during template rendering
  • A different type of iterative function
  • Test if value exists in several lists
  • Go and Python HMAC libraries give different results
  • Python Nested Loop Working Weirdly
  • Why is this not assigning the correct value?
  • 'numpy.ndarray' object is not callable
  • How to deal with globals in modules?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org