## How to find two items of a list with the same return value of a function on their attribute?

Given a basic class `Item`

:

class Item(object): def __init__(self, val): self.val = val

a list of objects of this class (the number of items can be much larger):

items = [ Item(0), Item(11), Item(25), Item(16), Item(31) ]

and a function `compute`

that process and return a value.

How to find two items of this list for which the function `compute`

return the same value when using the attribute `val`

? If nothing is found, an exception should be raised. If there are more than two items that match, simple return any two of them.

For example, let's define `compute`

:

def compute( x ): return x % 10

The excepted pair would be: `(Item(11), Item(31))`

.

Assuming the values returned by `compute`

are hashable (e.g., `float`

values), you can use a dict to store results.

And you don't need to do anything fancy, like a multidict storing all items that produce a result. As soon as you see a duplicate, you're done. Besides being simpler, this also means we short-circuit the search as soon as we find a match, without even calling `compute`

on the rest of the elements.

def find_pair(items, compute): results = {} for item in items: result = compute(item.val) if result in results: return results[result], item results[result] = item raise ValueError('No pair of items')

**How to call JavaScript code on multiple DIV elements without the ID ,** You can select these DIV elements, even though they don't have id attributes. In fact, they share the same class name “image”. Let's see a few If there are three items that have the same output value for compute, only the two firsts will be returned. @AChampion Afterthought, it is not mandatory that the pair is the two first elements that match. It could be any two elements of the list.

You can check the length of the set of resulting values:

class Item(object): def __init__(self, val): self.val = val def __repr__(self): return f'Item({self.val})' def compute(x): return x%10 items = [ Item(0), Item(11), Item(25), Item(16), Item(31)] c = list(map(lambda x:compute(x.val), items)) if len(set(c)) == len(c): #no two or more equal values exist in the list raise Exception("All elements have unique computational results")

To find values with similar computational results, a dictionary can be used:

from collections import Counter new_d = {i:compute(i.val) for i in items} d = Counter(new_d.values()) multiple = [a for a, b in new_d.items() if d[b] > 1]

Output:

[Item(11), Item(31)]

A slightly more efficient way to find if multiple objects of the same computational value exist is to use `any`

, requiring a single pass over the `Counter`

object, whereas using a `set`

with `len`

requires several iterations:

if all(b == 1 for b in d.values()): raise Exception("All elements have unique computational results")

**Return Multiple Match Results in Excel (2 methods),** The following example demonstrates the Find method on a List<T> that get; set; } public int PartId { get; set; } public override string ToString() { return "ID: " + public static void Main(string[] args) { FillList(); // Find a book by its ID. Elements(); // Evaluate each element and set set values in the book object. Attribute("id"). Find example. Here we consider the Find() method on List. Find accepts a Predicate, which we can specify as a lambda expression. It returns the first match.Predicate Lambda. Here: This code loops through each int value in the List, starting at the beginning, and tests each one to see if it is greater than 20. Return: The value 23 is returned

A dictionary `val_to_it`

that contains `Item`

s keyed by computed `val`

can be used:

val_to_it = {} for it in items: computed_val = compute(it.val) # Check if an Item in val_to_it has the same computed val dict_it = val_to_it.get(computed_val) if dict_it is None: # If not, add it to val_to_it so it can be referred to val_to_it[computed_val] = it else: # We found the two elements! res = [dict_it, it] break else: raise Exception( "Can't find two items" )

The `for`

block can be rewrite to handle `n`

number of elements:

for it in items: computed_val = compute(it.val) dict_lit = val_to_it.get(computed_val) if dict_lit is None: val_to_it[computed_val] = [it] else: dict_lit.append(it) # Check if we have the expected number of elements if len(dict_lit) == n: # Found n elements! res = dict_lit break

**List<T>.Find(Predicate<T>) Method,** loops from 2 to the given number; returns False as soon as a divisor is found Python has a built-in function all that returns True if all items are truthy If we wanted to be really silly, we could make such a list of boolean values like this: You can always reformat your code to use an if statement if you find it Using INDEX and MATCH Function to Match Two Columns in Excel and Return a Third. Let`s work on a different example where we will use two values from two different columns where the values exist in the same row. The return value will be from the third column and it will also be in the same row of the 2 values that will be given.

**Check Whether All Items Match a Condition in Python,** If function is None, the identity function is used and all the elements of list that are false Returns an attribute of an object. name is a string. default is an optional value to The hash value is the same for any two objects that compare as equals. a string. intern(string) Checks to see whether string is contained in an internal Note: In the formula, B2:B11 is the range which the matched instances locate in. A2:A11 is the range contains the certain value you will list all instances based on. And D2 contains the certain value. 2. Keep selecting the result cell, then drag the Fill Handle down to get the other matched instances. List first matched instance of a value with

**Python Essential Reference,** Return zero-based index in the list of the first item whose value is equal to x. in place (the arguments can be used for sort customization, see sorted() for their Note how the order of the for and if statements is the same in both these snippets. List comprehensions can contain complex expressions and nested functions:. It looks up a list and finds the k'th smallest value in the array. If k = 1 it will find the smallest. If k=2 it will find the second smallest value, and so on. The second instance of the ROW function is used to find k in our formula. In this example, ROW will return the row number of row 1, which is, of course, 1.

**5. Data Structures,** Instead it returns TRUE only if the object is a vector with no attributes apart from names. c(1, c(2, c(3, 4))) #> [1] 1 2 3 4 # the same as c(1, 2, 3, 4) #> [1] 1 2 3 4 Lists are different from atomic vectors because their elements can be of any type, Each of these attributes has a specific accessor function to get and set values. Duplicate Lookup or Lookup 1 value, return many for a table Part 1. Return winning bets for week from a football betting database. See a formula that will return multiple items when there are two