如何对元组的每个元素应用一个函数?

154 阅读3分钟

这篇文章告诉你如何将一个给定的函数应用于一个元组的每个元素。

将一个函数应用于元组的每个元素的最好方法是Python内置的 [map(function, iterable)](https://blog.finxter.com/python-map/ "Python map() — Finally Mastering the Python Map Function [+Video]")函数,它将一个函数和一个可迭代的元素作为参数,并将该函数应用于每个可迭代的元素。另一种方法是使用列表理解

注意:下面提供的所有解决方案都在Python 3.9.5 中得到了验证。

问题的提出

想象一下下面这个Python中的字符串元组。

my_tuple = ('you',  'cannot',  'exercise',  
            'away',  'a',  'bad',  'diet')

如何应用一个函数string.upper() 来对元组中的每个字符串进行大写

('YOU', 'CANNOT', 'EXERCISE', 'AWAY', 'A', 'BAD', 'DIET')

我将首先从*"天真的方法 "开始,之后再向你展示更多的Pythonic解决方案*。那么,让我们开始吧!

方法1:简单的For Loop

上面的问题,像其他许多问题一样,在Python中有一个相当简单的解决方案。

一个简单的解决方案是使用一个vanilla Python循环来迭代原始元组的每个元素。将函数应用于循环体中的每个元素,并将这些元素存储在一个可变的容器类型中,如一个列表。最后,使用构造函数创建一个新的元组,并将新元素作为 [tuple()](https://blog.finxter.com/python-tuple/)构造函数创建一个新的元组,并将新的元素作为参数传递。

结果是一个新元素的元组 - 这里是在应用函数后存储在变量new_tuple 中的 [string.upper()](https://blog.finxter.com/python-string-upper/)对Python元组的每个元素都应用了函数后,结果是一个新元素的元组--这里存储在变量。

my_tuple = ('you',  'cannot',  'exercise',  
            'away',  'a',  'bad',  'diet')

tmp = []
for element in my_tuple:
    # Apply function to each element here:
    tmp.append(element.upper())

# Create a new tuple here:
new_tuple = tuple(tmp)

print(new_tuple)
# ('YOU', 'CANNOT', 'EXERCISE', 'AWAY', 'A', 'BAD', 'DIET')

然而,这并不是处理这个问题的最Pythonic的方法。

方法2:map()

使用Python内置的 map() 函数是解决这个问题的最有效和最优雅的方法。map(function, iterable) 函数以一个函数和一个迭代器为参数,将给定的function 应用于iterable 的每个元素。

例如,为了将string.upper() 函数应用于一个 Python 元组的每个元素,使用map(str.upper, my_tuple) 函数来获得一个生成器对象。现在,使用tuple() 构造函数将结果转换为一个元组,你就解决了这个问题

这个方法在下面的代码片断中显示。

# 'my_tuple' is the original tuple whose string elements need to be
# fully uppercased. Note that 'my_tuple' is an object of the Python
# built-in Tuple class. Lists, Sets, Dicts and Tuples are considered
# iterables.
my_tuple = ('you',  'cannot',  'exercise',  'away',  'a',  'bad',  'diet')

# Use the upper() function of Python's built-in str class, to modify
# each element of the my_tuple iterable.
my_generic_iterable = map(str.upper, my_tuple)
  
# map() returns an iterable (or generator) object.
# It contains all the modified elements. Generators are temporary container
# objects. They can be iterated upon only once, to extract the elements
# within them. For example, use the 'tuple()' constructor to go thru each
# element of the 'my_generic_iterable' generator and generate a tuple.
new_tuple = tuple(my_generic_iterable)

print(new_tuple)
# Output:
# ['YOU', 'CANNOT', 'EXERCISE', 'AWAY', 'A', 'BAD', 'DIET']

方法3:生成器表达式

你可以使用生成器表达式将一个函数应用于元组的每个元素。

下面是如何实现这一目的。

my_tuple = ('you',  'cannot',  'exercise',  
            'away',  'a',  'bad',  'diet')
new_tuple = tuple(str.upper(x) for x in my_tuple)

print(new_tuple)
# Output:
# ['YOU', 'CANNOT', 'EXERCISE', 'AWAY', 'A', 'BAD', 'DIET']

生成器表达式类似于列表理解法。你可以在下面的视频中了解更多关于列表理解的信息--生成器表达式的工作原理类似,但更普遍适用。