Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python itertools.starmap() Function



The Pythonitertools.starmap() function is used to apply a given function to arguments taken from an iterable of tuples. It is similar to the built-inmap() function but instead of taking separate arguments, it expands each tuple as function arguments.

This function is particularly useful when working with functions that take multiple arguments and when the arguments are grouped in iterable pairs.

Syntax

Following is the syntax of the Python itertools.starmap() function −

itertools.starmap(function, iterable)

Parameters

This function accepts the following parameters −

  • function: The function to apply to each tuple of arguments.
  • iterable: An iterable containing tuples, where each tuple is unpacked as arguments to the function.

Return Value

This function returns an iterator that applies the function to each tuple of arguments.

Example 1

Following is an example of the Python itertools.starmap() function. Here, we apply a multiplication function to pairs of numbers −

import itertoolsdef multiply(a, b):   return a * bpairs = [(2, 3), (4, 5), (6, 7)]result = itertools.starmap(multiply, pairs)for value in result:   print(value)

Following is the output of the above code −

62042

Example 2

Here, we use itertools.starmap() function to calculate the power of numbers usingpow() function −

import itertoolspairs = [(2, 3), (3, 2), (4, 2), (5, 3)]result = itertools.starmap(pow, pairs)for value in result:   print(value)

Output of the above code is as follows −

8916125

Example 3

Now, we use itertools.starmap() function with a function that calculates the area of a rectangle given width and height −

import itertoolsdef area(width, height):   return width * heightrectangles = [(3, 4), (5, 6), (7, 2)]result = itertools.starmap(area, rectangles)for value in result:   print(value)

The result obtained is as shown below −

123014

Example 4

We can use itertools.starmap() function to process coordinate points by calculating their Euclidean distance from the origin −

import itertoolsimport mathdef distance(x, y):   return math.sqrt(x**2 + y**2)points = [(3, 4), (5, 12), (8, 15)]result = itertools.starmap(distance, points)for value in result:   print(value)

The result produced is as follows −

5.013.017.0
python_modules.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp