logo
down
shadow

Python: Finding a value in 1 list and finding that corresponding index in another list


Python: Finding a value in 1 list and finding that corresponding index in another list

By : Bob F.
Date : November 22 2020, 07:01 PM
Does that help My function is given a 'to_find_value' then I have 2 lists which are the same in length and index values. Once I find the index value in list 1 that 'to_find_value' is in, I want to take that index of list 2 and return the value found at list 2. , Something like:
code :
def f(a,b,c):
    return c[b.index(a)]
print(f('tree', ['bush', 'tree', 'shrub'], ['red', 'green', 'yellow']))
green


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
Finding first and last index of some value in a list in Python

Finding first and last index of some value in a list in Python


By : coffee
Date : March 29 2020, 07:55 AM
I wish this help you Sequences have a method index(value) which returns index of first occurrence - in your case this would be verts.index(value).
You can run it on verts[::-1] to find out the last index. Here, this would be len(verts) - 1 - verts[::-1].index(value)
Finding list of index corresponding to list of element of a dataframe in Python

Finding list of index corresponding to list of element of a dataframe in Python


By : Vadim Zylevich
Date : March 29 2020, 07:55 AM
I wish did fix the issue. IIUC you need isin if find first value of index:
code :
df[df['processed_col'].isin([element1, element2,..., elementN])].index[0]
df[df['processed_col'].isin([element1, element2,..., elementN])].index
df[df['processed_col'].isin([element1, element2,..., elementN])].index.tolist()
Python list finding with index

Python list finding with index


By : Tsutenkyo
Date : March 29 2020, 07:55 AM
should help you out I was wondering how would you find the index of a element in a list if you only had part of it. For example , Straightforward for loop:
code :
def find_starts(val, my_list):
    for i, v in my_list:
       if v.startswith(val):
           return i
Finding the value of a particular index in a Python list

Finding the value of a particular index in a Python list


By : Victor
Date : March 29 2020, 07:55 AM
it should still fix some issue You didn't write the second part of your if well. You first look at any(word in list2 for word in word_tokenize(sentence)) which returns a boolean. Then you try to extract the last element of this boolean ([-1]) which return an error.
No need to use nltk library here, you can do it with just .split():
code :
negation ='no,not,never'.split(',')
list2 = 'miss,loss,gone,give up,lost'.split(',')

def f(sentence):
    if any(word in list2 for word in sentence.split()) and not any(word in negation for word in sentence.split()):
        print 'sad'
    else:
        print 'not sad'

l = ['loss money', 'I miss him', 'I not miss him']
for e in l:
    f(e)
# Outputs: sad / sad / not sad
negation = {'no', 'not', 'never'}
list2 = {'miss', 'loss', 'gone', 'give up', 'lost'}

def f(sentence):
    s = sentence.split()
    l = [s.index(word) for word in s if word in list2]
    # Will returns list of indices (of sentence) where word is in list2
    if len(l) > 0:
        for e in l:
            # Check previous word
            if s[e-1] not in negation:
                print 'sad'
            else:
                print 'not sad'
    else:
        print 'happy'

l = ['loss money', 'I miss him', 'I not miss him', 'happy new year', 'I am not here I am gone']
for e in l:
    f(e)
# sad / sad / not sad / happy / sad
Related Posts Related Posts :
  • Percent signs in windows path
  • How to add a random number to a subsection of a numpy array?
  • How to generate all the values of an iterable besides the last few?
  • Searching by both class and range in XPath
  • Python code execution in Perl interpreter
  • Best Way to Include Variable in Python3
  • Serialize the @property methods in a Python class
  • What is the most platform- and Python-version-independent way to make a fast loop for use in Python?
  • Good way to edit the previous defined class in ipython
  • Bounced email on Google App Engine
  • Search jpeg files using python
  • Dynamically create class attributes
  • python unichr problem
  • Python beginner, strange output problem
  • can't install mysqlclient on mac os x mojave
  • Error indicates flattened dimensions when loading pre-trained network
  • how to replace underlines with words?
  • Adding through iteration
  • Use OpenCV on deployed Flask app (Heroku)
  • How to skip interstitial in a django view if a user hits the back button?
  • Any Naive Bayesian Classifier in python?
  • Python 2.5.2: remove what found between two lines that contain two concrete strings
  • Python 2.5.2 script that add "The function starts here" to all the functions of the files of a directory
  • HttpResponseRedirect question
  • Python socket error on UDP data receive. (10054)
  • Encoding issues with cloud ml
  • numpy.where - Weird behaviour: new elements spawning from nowhere?
  • I can't move my player in pygame, can you figure why?
  • Weird error I receive from Tkinter in Python
  • Using a Zapier Custom Request Webhook with JSON Web Tokens
  • Keras: Use categorical_crossentropy without one-hot encoded array of targets
  • Does python's httplib.HTTPConnection block?
  • Do alternate python implementation version numbers imply that they provide the same syntax?
  • Searching for specific HTML string using Python
  • python sax error "junk after document element"
  • MySql: How to know if an entry is compressed or not
  • Return a list of imported Python modules used in a script?
  • Returning a list in this recursive coi function in python
  • Python2.6 Decimal to Octal
  • Appengine Apps Vs Google bot web crawler
  • Changing models in django results in broken database?
  • Global variable functions
  • Using lambda inside a function
  • How to open a file, replace some strings, and save updates to the same file?
  • How to move the beginning of an input to the and?
  • If else fill variable if empty list
  • Pandas: Find and print all floats in column
  • sqlite3.OperationalError: database is locked - non-threaded application
  • How to implement mib module in net-snmp with python?
  • Does Python/Scipy have a firls( ) replacement (i.e. a weighted, least squares, FIR filter design)?
  • sorl-thumbnail and file renaming
  • Python -- what is NOT in 2.7 that IS in 3.1? So many things have been back-ported, what is NOT?
  • How to make a Django model fields calculated at runtime?
  • Django - Threading in views without hanging the server
  • Python: Why is my POST requests not working?
  • Tried to add a value to a while condition, but it doesn't go back
  • How do I exit a while-true loop after 5 tries?
  • win python3 Multithreading
  • Compare 2 dictionaries in python
  • How to debug "str object is not callable"?
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk