Get first list index containing sub-string?

2024/11/21 2:31:32

For lists, the method list.index(x) returns the index in the list of the first item whose value is x. But if I want to look inside the list items, and not just at the whole items, how do I make the most Pythoninc method for this?

For example, with

l = ['the cat ate the mouse','the tiger ate the chicken','the horse ate the straw']

this function would return 1 provided with the argument tiger.

Answer

A non-slicky method:

def index_containing_substring(the_list, substring):for i, s in enumerate(the_list):if substring in s:return ireturn -1
https://en.xdnf.cn/q/26251.html

Related Q&A

TypeError: Invalid dimensions for image data when plotting array with imshow()

For the following code# Numerical operation SN_map_final = (new_SN_map - mean_SN) / sigma_SN # Plot figure fig12 = plt.figure(12) fig_SN_final = plt.imshow(SN_map_final, interpolation=nearest) plt.col…

How to give delay between each requests in scrapy?

I dont want to crawl simultaneously and get blocked. I would like to send one request per second.

preprocess_input() method in keras

I am trying out sample keras code from the below keras documentation page, https://keras.io/applications/What preprocess_input(x) function of keras module does in the below code? Why do we have to do …

How to calculate precision and recall in Keras

I am building a multi-class classifier with Keras 2.02 (with Tensorflow backend),and I do not know how to calculate precision and recall in Keras. Please help me.

Django set range for integer model field as constraint

I have a django model,class MyModel(models.Model)qty = model.IntegerField()where I want to set constraint for qty something like this, >0 or <0,i.e the qty can be negative or positive but can no…

Increase resolution with word-cloud and remove empty border

I am using word cloud with some txt files. How do I change this example if I wanted to 1) increase resolution and 2) remove empty border. #!/usr/bin/env python2 """ Minimal Example =====…

How can I check if a list index exists?

Seems as thoughif not mylist[1]:return FalseDoesnt work.

Check if space is in a string

in word == TrueIm writing a program that checks whether the string is a single word. Why doesnt this work and is there any better way to check if a string has no spaces/is a single word..

Django F expressions joined field

So I am trying to update my model by running the following: FooBar.objects.filter(something=True).update(foobar=F(foo__bar))but I get the following error: FieldError: Joined field references are not pe…

How do I unit test PySpark programs?

My current Java/Spark Unit Test approach works (detailed here) by instantiating a SparkContext using "local" and running unit tests using JUnit.The code has to be organized to do I/O in one f…