Call Int() Function on Every List Element

Call int() function on every list element?

This is what list comprehensions are for:

numbers = [ int(x) for x in numbers ]

Apply function to each element of a list

Using the built-in standard library map:

>>> mylis = ['this is test', 'another test']
>>> list(map(str.upper, mylis))
['THIS IS TEST', 'ANOTHER TEST']

In Python 2.x, map constructed the desired new list by applying a given function to every element in a list.

In Python 3.x, map constructs an iterator instead of a list, so the call to list is necessary. If you are using Python 3.x and require a list the list comprehension approach would be better suited.

What python built-in function can apply some function to every element of list in-place?

There's no built-in function, but you can accomplish the same result using map and slice assignment.

array[:] = map(sqr, array)

(If you needed an expression rather than a statement, you could use the monstrosity

array.__setitem__(slice(None), map(sqr, array))

which is essentially how the slice assignment is implemented.
)

Short way to apply a function to all elements in a list in golang

I would do exactly as you did, with a few tweaks to fix typos

import (
"fmt"
"strconv"
"strings"
)

func main() {
list := []int{1,2,3}

var list2 []string
for _, x := range list {
list2 = append(list2, strconv.Itoa(x * 2)) // note the = instead of :=
}

str := strings.Join(list2, ", ")
fmt.Println(str)
}

Function is not being called on every element of list

From the code, and without an explicit failing test case scenario, what could be happening is mentioned by John Coleman in the comments, which is a hole in the ranges you test for in the comment function. Together with some code cleanup here's what I would write:

def percentage(a, b):
return 100 * (float(a) / float(b))

def comment(a, b):
if percentage(a, b) <= 29:
print("That is a low percentage")

elif percentage(a, b) <= 69: # notice the range from above 29
print("That is a medium percentage")

elif percentage(a, b) > 69: # notice the range from above 69
print("That is a high percentage")

def main():
rnumber = 500
perclist = [int(e) for e in input("Enter the percentages you want to comment: (separated by spaces) ").split()]
percprint = [(e*5) for e in perclist]

print("Total inputs: " + len(perclist))
print(percprint)
for e in percprint:
comment(e, rnumber)

main()

If you want to include a progress counter as per your comment, you could do something like:

def comment(a, b, i):
if percentage(a, b) <= 29:
print("[%s] That is a low percentage" % i)

elif percentage(a, b) <= 69: # notice the range from above 29
print("[%s] That is a medium percentage" % i)

elif percentage(a, b) > 69: # notice the range from above 69
print("[%s] That is a high percentage" % i)

And use enumerate in main() as:

    for i, e in enumerate(percprint):
comment(e, rnumber, i+1)

If - instead - you want to include the value being commented, you could do something like:

def comment(a, b):
if percentage(a, b) <= 29:
print("[%s] That is a low percentage" % a)

elif percentage(a, b) <= 69: # notice the range from above 29
print("[%s] That is a medium percentage" % a)

elif percentage(a, b) > 69: # notice the range from above 69
print("[%s] That is a high percentage" % a)

and main() remains same as the first version in this answer.

How can I call a method on each element of a List?

UPDATE:

See aaiezza's answer for a Java 8 solution using a lambda expression.

Original pre-Java 8 answer:

The effect can be achieved with Guava, the Function implementation is already more verbose than what you have:

List<Car> cars = //...

Function<Car, String> carsToNames = new Function<Car, String>() {
@Override
public String apply(Car car) {
return car.getName();
}
}

List<String> names = Lists.transform(cars, carsToNames);

(Keep in mind that Lists.transform returns a view that will apply the function lazily - if you want an immediate copy, you need to copy the returned list into a new list.)

So this doesn't help you shorten your code, but it's an example of how verbose it is to achieve your desired affect in Java.

Edit: You might have a look at lambdaj, a library that seems to approach what you're looking for. I haven't tried this out myself, but the homepage shows this example:

List<Person> personInFamily = asList(new Person("Domenico"), new Person("Mario"), new Person("Irma"));
forEach(personInFamily).setLastName("Fusco");


Related Topics



Leave a reply



Submit