PYTHON : lambda函数与map、filter和reduce等函数式

目录

lambda函数简介

lambda函数和map结合

        1. 将列表中的每个元素加倍:

        2. 将字符串列表中的每个字符串转换为大写:

        3. 计算列表中每个元素的平方:

        4. 提取列表中每个字符串的长度:

        5. 将数字列表转换为字符串列表:

lambda函数和filter结合

        1. 筛选出列表中的偶数:

        2. 筛选出字符串列表中长度大于等于5的字符串:

        3. 筛选出包含字母"E"的字符串:

        4. 筛选出列表中的正数:

        5. 筛选出字典中值大于等于5的项:

lambda函数和reduce结合

总结:常见的函数和lambda函数组合使用的示例:

lambda函数

map函数

filter函数

reduce函数


lambda函数简介

lambda函数是由数学家阿隆佐·丘奇(Alonzo Church)在 20 世纪 30 年代提出的,后来被引入到编程语言中。lambda函数是一种匿名函数,可以在需要函数的地方使用,并且通常用于简单的函数操作。

lambda函数的主要用途是在需要一个函数,但又不想费力定义一个完整的函数时使用。它通常用于某些函数式编程的场景,例如在函数式编程语言中或者在Python等支持函数式编程的语言中经常会用到lambda函数。以下是lambda函数的一个简单示例,在Python中使用lambda函数创建一个简单的加法函数:

add = lambda x, y: x + y
print(add(3, 5))  # 输出:8

在这个例子中,`lambda x, y: x + y` 定义了一个接受两个参数 x 和 y,返回它们的和的匿名函数。然后我们使用这个lambda函数将3和5相加。

lambda函数通常与map、filter和reduce等函数式编程工具一起使用。下面是它们的基本用法:

lambda函数和map结合

map函数:map函数接受一个函数和一个可迭代对象作为参数,它将函数应用于可迭代对象的每个元素,并返回一个包含结果的迭代器。 当使用lambda函数和map结合时,可以进行各种简洁的数据转换和处理。以下是5个示例:

        1. 将列表中的每个元素加倍:
nums = [1, 2, 3, 4, 5]
doubled_nums = list(map(lambda x: x * 2, nums))
print(doubled_nums)  # 输出:[2, 4, 6, 8, 10]
        2. 将字符串列表中的每个字符串转换为大写:
words = ["apple", "banana", "cherry"]
upper_words = list(map(lambda x: x.upper(), words))
print(upper_words)  # 输出:['APPLE', 'BANANA', 'CHERRY']
        3. 计算列表中每个元素的平方:
nums = [1, 2, 3, 4, 5]
squared_nums = list(map(lambda x: x**2, nums))
print(squared_nums)  # 输出:[1, 4, 9, 16, 25]
        4. 提取列表中每个字符串的长度:
words = ["apple", "banana", "cherry"]
word_lengths = list(map(lambda x: len(x), words))
print(word_lengths)  # 输出:[5, 6, 6]
        5. 将数字列表转换为字符串列表:
nums = [1, 2, 3, 4, 5]
str_nums = list(map(lambda x: str(x), nums))
print(str_nums)  # 输出:['1', '2', '3', '4', '5']

lambda函数和filter结合

filter函数:filter函数接受一个函数和一个可迭代对象作为参数,它使用函数来筛选可迭代对象中的元素,并返回一个包含符合条件的元素的迭代器。当使用lambda函数和filter结合时,可以根据特定条件筛选和过滤数据。以下是5个示例:

        1. 筛选出列表中的偶数:
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_nums = list(filter(lambda x: x % 2 == 0, nums))
print(even_nums)  # 输出:[2, 4, 6, 8, 10]
        2. 筛选出字符串列表中长度大于等于5的字符串:
words = ["apple", "banana", "cherry", "date", "elderberry"]
long_words = list(filter(lambda x: len(x) >= 5, words))
print(long_words)  # 输出:['apple', 'banana', 'cherry', 'elderberry']
        3. 筛选出包含字母"E"的字符串:
words = ["apple", "banana", "cherry", "date", "elderberry"]
e_words = list(filter(lambda x: 'e' in x.lower(), words))
print(e_words)  # 输出:['apple', 'date', 'elderberry']
        4. 筛选出列表中的正数:
numbers = [5, -3, 8, -2, 0, -7, 10]
positive_nums = list(filter(lambda x: x > 0, numbers))
print(positive_nums)  # 输出:[5, 8, 10]
        5. 筛选出字典中值大于等于5的项:
data = {'a': 3, 'b': 6, 'c': 2, 'd': 8, 'e': 4}
filtered_data = dict(filter(lambda x: x[1] >= 5, data.items()))
print(filtered_data)  # 输出:{'b': 6, 'd': 8}

lambda函数和reduce结合

        reduce函数:在Python 3中,reduce函数被移到了functools模块中。reduce函数接受一个函数和一个可迭代对象作为参数,它对可迭代对象中的元素进行累积计算。

from functools import reduce

# 示例1:计算列表中所有元素的和
nums = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, nums)
print(total)  # 输出:15

# 示例2:计算列表中所有元素的乘积
nums = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, nums)
print(product)  # 输出:120

# 示例3:找出列表中的最大值
nums = [3, 8, 1, 6, 2, 5]
max_num = reduce(lambda x, y: x if x > y else y, nums)
print(max_num)  # 输出:8

# 示例4:合并字符串列表
words = ["hello", "world", "how", "are", "you"]
combined = reduce(lambda x, y: x + " " + y, words)
print(combined)  # 输出:hello world how are you

# 示例5:使用reduce来实现阶乘
n = 5
factorial = reduce(lambda x, y: x * y, range(1, n+1))
print(factorial)  # 输出:120

总结:常见的函数和lambda函数组合使用的示例:

# 1. map:对可迭代对象中的每个元素应用lambda函数
result = list(map(lambda x: x*2, [1, 2, 3, 4]))
print(result)  # 输出:[2, 4, 6, 8]

# 2. filter:使用lambda函数过滤可迭代对象中的元素
result = list(filter(lambda x: x > 5, [3, 7, 2, 8, 5]))
print(result)  # 输出:[7, 8]

# 3. sorted:使用lambda函数定义排序规则
result = sorted([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5], key=lambda x: -x)
print(result)  # 输出:[9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]

# 4. max/min:使用lambda函数找出最大值或最小值
max_num = max([3, 7, 2, 8, 5], key=lambda x: x)
print(max_num)  # 输出:8

# 5. reduce:使用lambda函数对可迭代对象中的元素进行累积计算
from functools import reduce
result = reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])
print(result)  # 输出:15

# 6. any/all:使用lambda函数对可迭代对象中的元素进行条件判断
result_any = any(map(lambda x: x > 10, [3, 7, 2, 8, 5]))
result_all = all(map(lambda x: x > 0, [3, 7, 2, 8, 5]))
print(result_any, result_all)  # 输出:False True

这些是lambda函数可以与一些常见函数组合使用的示例。除此之外,lambda函数还可以结合其他自定义函数、类方法等进行灵活的编程。

lambda函数

#在Python中,lambda函数是一种匿名函数,也称为"lambda表达式"。它是一种简洁的方式定义一个只包含单
#个表达式的函数。lambda函数的基本语法为:lambda arguments: expression,其中arguments是函数的
#参数,expression是函数的返回值。

#1. 将两个数相加:
add = lambda x, y: x + y
result = add(3, 4)
print(result)  # 输出:7

#2. 计算一个数的平方:
square = lambda x: x**2
result = square(5)
print(result)  # 输出:25

#3. 判断一个数是否为偶数:
is_even = lambda x: x%2 == 0
result = is_even(6)
print(result)  # 输出:True

#4. 取一个字符串的长度:
length = lambda s: len(s)
result = length("hello")
print(result)  # 输出:5

#5. 将两个数相乘:
multiply = lambda x, y: x * y
result = multiply(3, 4)
print(result)  # 输出:12

#6. 将一个字符串转换为大写:
uppercase = lambda s: s.upper()
result = uppercase("hello")
print(result)  # 输出:HELLO

#7. 判断一个数是否为质数:
is_prime = lambda x: all(x % i != 0 for i in range(2, int(x**0.5)+1)) and x > 1
result = is_prime(7)
print(result)  # 输出:True

#8. 取一个数字的绝对值:
absolute = lambda x: abs(x)
result = absolute(-5)
print(result)  # 输出:5

#9. 将一个字符串转换为小写:
lowercase = lambda s: s.lower()
result = lowercase("HELLO")
print(result)  # 输出:hello

#10. 判断一个字符是否为元音字母:
is_vowel = lambda c: c.lower() in 'aeiou'
result = is_vowel('A')
print(result)  # 输出:True

#11. 获取一个字典中的值:
get_value = lambda d, k: d.get(k)
result = get_value({'a': 1, 'b': 2}, 'b')
print(result)  # 输出:2

#12. 求两个数的最大值:
max_num = lambda x, y: x if x > y else y
result = max_num(5, 7)
print(result)  # 输出:7

#13. 将一个字符串逆序输出:
reverse_string = lambda s: s[::-1]
result = reverse_string("hello")
print(result)  # 输出:olleh

#14. 判断一个字符串是否为回文串:
is_palindrome = lambda s: s == s[::-1]
result = is_palindrome("radar")
print(result)  # 输出:True

#15. 将一个列表的元素转换为大写:
uppercase_list = lambda lst: [x.upper() for x in lst]
result = uppercase_list(['apple', 'banana', 'cherry'])
print(result)  # 输出:['APPLE', 'BANANA', 'CHERRY']

#16. 计算两个数的平均值:
average = lambda x, y: (x + y) / 2
result = average(4, 6)
print(result)  # 输出:5.0

#17. 将一个列表的元素求和:
sum_list = lambda lst: sum(lst)
result = sum_list([1, 2, 3, 4, 5])
print(result)  # 输出:15

#18. 判断一个字符串是否为纯数字:
is_digit = lambda s: s.isdigit()
result = is_digit("123")
print(result)  # 输出:True

#19. 判断一个数是否为完全平方数:
is_perfect_square = lambda x: int(x**0.5)**2 == x
result = is_perfect_square(16)
print(result)  # 输出:True

#20. 将一个列表的元素进行排序:
sort_list = lambda lst: sorted(lst)
result = sort_list([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5])
print(result)  # 输出:[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

#这些示例展示了如何使用lambda函数来定义简单的功能,从而实现各种操作。

map函数

# 在Python中,map函数是一个内置函数,用于将一个函数应用到可迭代对象(如列表、元组等)的所有元素,
# 然后返回一个迭代器。map函数的基本语法为:map(function, iterable),其中function是要应用的函  
# 数,iterable是要处理的可迭代对象。以下是20个使用map函数的示例:

# 1. 将列表中的每个元素求平方:
nums = [1, 2, 3, 4, 5]
squared_nums = map(lambda x: x**2, nums)
result = list(squared_nums)
print(result)  # 输出:[1, 4, 9, 16, 25]

# 2. 将字符串列表中的每个字符串转换为大写:
words = ['apple', 'banana', 'cherry']
uppercase_words = map(str.upper, words)
result = list(uppercase_words)
print(result)  # 输出:['APPLE', 'BANANA', 'CHERRY']

# 3. 将两个列表对应位置的元素相加:
list1 = [1, 2, 3, 4, 5]
list2 = [6, 7, 8, 9, 10]
sums = map(lambda x, y: x + y, list1, list2)
result = list(sums)
print(result)  # 输出:[7, 9, 11, 13, 15]

# 4. 将元组中每个元素的长度计算出来:
tuple_of_words = ('apple', 'banana', 'cherry', 'date')
lengths = map(len, tuple_of_words)
result = list(lengths)
print(result)  # 输出:[5, 6, 6, 4]

# 5. 使用map函数对多个列表的元素进行组合:
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
combined = map(lambda x, y: str(x) + y, list1, list2)
result = list(combined)
print(result)  # 输出:['1a', '2b', '3c']

# 6. 对字典中的值应用函数:
dict_of_nums = {'a': 3, 'b': 5, 'c': 7}
new_dict = map(lambda x: x**2, dict_of_nums.values())
result = list(new_dict)
print(result)  # 输出:[9, 25, 49]

# 7. 对二维列表中的每个元素进行求和:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
sums = map(sum, matrix)
result = list(sums)
print(result)  # 输出:[6, 15, 24]

# 8. 将字符串列表中的每个字符串转换为整数:
str_nums = ['1', '2', '3', '4', '5']
int_nums = map(int, str_nums)
result = list(int_nums)
print(result)  # 输出:[1, 2, 3, 4, 5]

# 9. 对列表中的元素进行格式化输出:
names = ['Alice', 'Bob', 'Charlie']
formatted_names = map(lambda x: f'Hello, {x}!', names)
result = list(formatted_names)
print(result)  # 输出:['Hello, Alice!', 'Hello, Bob!', 'Hello, Charlie!']

# 10. 将元组中每个元素的首字母大写:
tuple_of_words = ('apple', 'banana', 'cherry', 'date')
capitalized_words = map(lambda x: x.capitalize(), tuple_of_words)
result = list(capitalized_words)
print(result)  # 输出:['Apple', 'Banana', 'Cherry', 'Date']

# 11. 对列表中的每个元素进行乘以2再加1的操作:
nums = [1, 2, 3, 4, 5]
modified_nums = map(lambda x: x*2+1, nums)
result = list(modified_nums)
print(result)  # 输出:[3, 5, 7, 9, 11]

# 12. 将二维列表中的每个元素进行平均值计算:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
averages = map(lambda x: sum(x)/len(x), matrix)
result = list(averages)
print(result)  # 输出:[2.0, 5.0, 8.0]

# 13. 将字符串中的每个字符转换为ASCII码:
text = "hello"
ascii_codes = map(ord, text)
result = list(ascii_codes)
print(result)  # 输出:[104, 101, 108, 108, 111]

# 14. 使用map函数对多个列表中的元素进行格式化组合:
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
combined = map(lambda x, y: f'{x}-{y}', list1, list2)
result = list(combined)
print(result)  # 输出:['1-a', '2-b', '3-c']

# 15. 对字典中的值进行四舍五入:
dict_of_nums = {'a': 3.14, 'b': 5.67, 'c': 7.89}
rounded_values = map(round, dict_of_nums.values())
result = list(rounded_values)
print(result)  # 输出:[3, 6, 8]

# 16. 对列表中的元素进行开平方操作:
nums = [1, 4, 9, 16, 25]
squared_root = map(lambda x: x**0.5, nums)
result = list(squared_root)
print(result)  # 输出:[1.0, 2.0, 3.0, 4.0, 5.0]

# 17. 将字符串列表中的每个字符串转换为长度大于5的布尔值:
words = ['apple', 'banana', 'cherry', 'date']
length_check = map(lambda x: len(x) > 5, words)
result = list(length_check)
print(result)  # 输出:[False, True, True, False]

# 18. 使用map函数对多个列表的元素进行累加:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
cumulative_sum = map(lambda x, y: x + y, list1, list2)
result = list(cumulative_sum)
print(result)  # 输出:[5, 7, 9]

# 19. 将元组中每个元素的首字母提取出来:
tuple_of_words = ('apple', 'banana', 'cherry', 'date')
first_letters = map(lambda x: x[0], tuple_of_words)
result = list(first_letters)
print(result)  # 输出:['a', 'b', 'c', 'd']

# 20. 对列表中的每个元素进行乘以自身的操作:
nums = [2, 3, 4, 5, 6]
squared_self = map(lambda x: x*x, nums)
result = list(squared_self)
print(result)  # 输出:[4, 9, 16, 25, 36]

# 这些示例展示了如何使用map函数对不同类型的可迭代对象进行处理,从而实现各种功能。

filter函数

#在Python中,`filter()`函数是一个内置函数,用于从可迭代对象中筛选出符合特定条件的元素,并返回一
#个迭代器对象。

#`filter()`函数的语法如下:
filter(function, iterable)
#其中,`function`是一个用于筛选元素的函数,`iterable`是一个可迭代对象,如列表、元组、集合等。

#`filter()`函数会遍历可迭代对象中的每个元素,将其传递给`function`函数进行判断。如果`function`函
#数返回`True`,则该元素会被保留在结果中,否则会被过滤掉。下面是20个使用`filter()`函数的示例:

#1. 过滤出列表中的偶数:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # 输出 [2, 4, 6, 8, 10]

#2. 过滤出字符串列表中长度大于等于5的字符串:
words = ["apple", "banana", "kiwi", "orange", "pineapple"]
long_words = list(filter(lambda x: len(x) >= 5, words))
print(long_words)  # 输出 ["apple", "banana", "orange", "pineapple"]

#3. 过滤出字典中值为正数的键值对:
numbers = {"a": 10, "b": -5, "c": 20, "d": -3, "e": 8}
positive_numbers = dict(filter(lambda item: item[1] > 0, numbers.items()))
print(positive_numbers)  # 输出 {"a": 10, "c": 20, "e": 8}

#4. 过滤出元组中小于10的元素:
t = (1, 11, 5, 7, 20, 3)
filtered_tuple = tuple(filter(lambda x: x < 10, t))
print(filtered_tuple)  # 输出 (1, 5, 7, 3)

#5. 过滤出集合中大于100的元素:
s = {50, 120, 80, 200, 150}
filtered_set = set(filter(lambda x: x > 100, s))
print(filtered_set)  # 输出 {120, 150, 200}

#6. 过滤出列表中不为空的字符串:
strings = ["", "hello", "", "world", ""]
non_empty_strings = list(filter(lambda x: x != "", strings))
print(non_empty_strings)  # 输出 ["hello", "world"]

#7. 过滤出字典中值为奇数的键:
numbers = {"a": 10, "b": 15, "c": 8, "d": 21, "e": 12}
odd_keys = list(filter(lambda item: item[1] % 2 != 0, numbers.items()))
print(odd_keys)  # 输出 [("b", 15), ("d", 21)]

#8. 过滤出列表中大于平均值的数:
numbers = [1, 5, 3, 7, 9, 2, 4, 6, 8]
average = sum(numbers) / len(numbers)
greater_than_average = list(filter(lambda x: x > average, numbers))
print(greater_than_average)  # 输出 [5, 7, 9, 6, 8]

#9. 过滤出字符串列表中以大写字母开头的字符串:
words = ["Apple", "banana", "Cat", "Dog", "elephant"]
uppercase_words = list(filter(lambda x: x[0].isupper(), words))
print(uppercase_words)  # 输出 ["Apple", "Cat", "Dog"]

#10. 过滤出字典中值为列表的键值对:
data = {"name": "John", "age": 25, "hobbies": ["reading", "coding"], "city": "New York"}
list_value_pairs = dict(filter(lambda item: isinstance(item[1], list), data.items()))
print(list_value_pairs)  # 输出 {"hobbies": ["reading", "coding"]}

#11. 过滤出列表中的负数:
numbers = [1, -2, 3, -4, 5, -6]
negative_numbers = list(filter(lambda x: x < 0, numbers))
print(negative_numbers)  # 输出 [-2, -4, -6]

#12. 过滤出字符串列表中包含字母"a"的字符串:
words = ["apple", "banana", "kiwi", "orange", "pineapple"]
contains_a = list(filter(lambda x: "a" in x, words))
print(contains_a)  # 输出 ["apple", "banana", "orange", "pineapple"]

#13. 过滤出字典中键的长度大于等于3的键值对:
data = {"name": "John", "age": 25, "hobbies": ["reading", "coding"], "city": "New York"}
long_keys = dict(filter(lambda item: len(item[0]) >= 3, data.items()))
print(long_keys)  # 输出 {"name": "John", "age": 25, "hobbies": ["reading", "coding"]}

#14. 过滤出元组中不是数字的元素:
t = (1, "hello", 3.14, "world", 5)
non_numeric_values = tuple(filter(lambda x: not isinstance(x, (int, float)), t))
print(non_numeric_values)  # 输出 ("hello", "world")

#15. 过滤出集合中不是偶数的元素:
s = {2, 4, 6, 7, 8, 9}
odd_numbers = set(filter(lambda x: x % 2 != 0, s))
print(odd_numbers)  # 输出 {7, 9}

#16. 过滤出列表中长度为偶数的字符串:
words = ["apple", "banana", "kiwi", "orange", "pineapple"]
even_length_words = list(filter(lambda x: len(x) % 2 == 0, words))
print(even_length_words)  # 输出 ["banana", "kiwi"]

#17. 过滤出字典中值为字符串的键值对:
data = {"name": "John", "age": 25, "city": "New York", "occupation": "engineer"}
string_value_pairs = dict(filter(lambda item: isinstance(item[1], str), data.items()))
print(string_value_pairs)  # 输出 {"name": "John", "city": "New York", "occupation": "engineer"}

#18. 过滤出列表中不是None的元素:
items = [1, None, "hello", None, 3.14, None]
non_none_items = list(filter(lambda x: x is not None, items))
print(non_none_items)  # 输出 [1, "hello", 3.14]

#19. 过滤出字典中值为奇数的键:
numbers = {"a": 10, "b": 15, "c": 8, "d": 21, "e": 12}
odd_keys = list(filter(lambda key: numbers[key] % 2 != 0, numbers))
print(odd_keys)  # 输出 ["b", "d"]

#20. 过滤出集合中不包含字母"e"的元素:
s = {"apple", "banana", "kiwi", "orange", "pineapple"}
no_e_words = set(filter(lambda x: "e" not in x, s))
print(no_e_words)  # 输出 {"kiwi"}

#这是一些使用`filter()`函数的例子,可以根据具体的需求和条件来筛选出符合要求的元素。

reduce函数

#在Python中,`reduce()`函数是`functools`模块中的一个函数,用于对一个序列进行累积操作,返回一个
#单一的结果。它接受两个参数:一个函数和一个可迭代对象。

#`reduce()`函数会将可迭代对象中的元素依次传递给函数,然后将函数的结果与下一个元素继续进行运算,直
#到遍历完所有元素,最后返回一个累积的结果。

#需要注意的是,使用`reduce()`函数前需要先导入`functools`模块,如下所示:
from functools import reduce

#以下是20个使用`reduce()`函数的示例:

#1. 计算列表中所有元素的和:
numbers = [1, 2, 3, 4, 5]
sum = reduce(lambda x, y: x + y, numbers)
print(sum)  # 输出 15

#2. 求列表中所有元素的乘积:
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(product)  # 输出 120

#3. 将列表中的数字转换为整数:
numbers = ["1", "2", "3", "4", "5"]
integers = reduce(lambda x, y: int(x) + int(y), numbers)
print(integers)  # 输出 15

#4. 连接字符串列表中的所有字符串:
words = ["Hello", " ", "world", "!"]
sentence = reduce(lambda x, y: x + y, words)
print(sentence)  # 输出 "Hello world!"

#5. 查找列表中的最大值:
numbers = [5, 2, 8, 1, 4]
max_value = reduce(lambda x, y: x if x > y else y, numbers)
print(max_value)  # 输出 8

#6. 查找列表中的最小值:
numbers = [5, 2, 8, 1, 4]
min_value = reduce(lambda x, y: x if x < y else y, numbers)
print(min_value)  # 输出 1

#7. 将字符串列表中的所有字符串连接成一个句子:
words = ["I", " ", "love", " ", "Python", "."]
sentence = reduce(lambda x, y: x + y, words)
print(sentence)  # 输出 "I love Python."

#8. 计算列表中所有元素的平均值:
numbers = [1, 2, 3, 4, 5]
average = reduce(lambda x, y: x + y, numbers) / len(numbers)
print(average)  # 输出 3.0

#9. 将列表中的字符串元素转换为大写:
words = ["hello", "world", "python"]
uppercase_words = reduce(lambda x, y: x + y.upper(), words, "")
print(uppercase_words)  # 输出 "HELLOWORLDPYTHON"

#10. 检查列表中的所有元素是否为真:
values = [True, True, False, True]
all_true = reduce(lambda x, y: x and y, values)
print(all_true)  # 输出 False

#11. 检查列表中是否存在至少一个奇数:
numbers = [2, 4, 6, 7, 8, 10]
has_odd = reduce(lambda x, y: x or y % 2 != 0, numbers, False)
print(has_odd)  # 输出 True

#12. 将列表中的字符串元素转换为整数:
numbers = ["1", "2", "3", "4", "5"]
integers = reduce(lambda x, y: int(x) + int(y), numbers)
print(integers)  # 输出 15

#13. 将列表中的元素按照指定的操作符进行运算:
from functools import reduce
import operator

numbers = [1, 2, 3, 4, 5]
result = reduce(operator.mul, numbers)
print(result)  # 输出 120

#14. 将二维列表展平为一维列表:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = reduce(lambda x, y: x + y, matrix)
print(flattened)  # 输出 [1, 2, 3, 4, 5, 6, 7, 8, 9]

#15. 统计字符串列表中各个字符的出现次数:
from functools import reduce
import collections

words = ["apple", "banana", "cherry"]
char_count = reduce(lambda x, y: collections.Counter(x) + collections.Counter(y), words)
print(char_count)  # 输出 {'a': 3, 'p': 2, 'l': 1, 'e': 3, 'b': 1, 'n': 2, 'c': 2, 'h': 1, 'e': 3, 'r': 2, 'y': 1}

#16. 检查列表中的所有元素是否为偶数:
numbers = [2, 4, 6, 8, 10]
all_even = reduce(lambda x, y: x and y % 2 == 0, numbers)
print(all_even)  # 输出 True

#17. 将字符串列表中的所有字符串转换为小写:
words = ["HELLO", "WORLD", "PYTHON"]
lowercase_words = reduce(lambda x, y: x + y.lower(), words, "")
print(lowercase_words)  # 输出 "helloworldpython"

#18. 将列表中的元素按照指定的顺序连接成一个字符串:
numbers = [1, 2, 3, 4, 5]
result = reduce(lambda x, y: str(x) + str(y), numbers)
print(result)  # 输出 "12345"

#19. 将列表中的元素进行累加,但只保留偶数元素:
numbers = [1, 2, 3, 4, 5]
sum_even = reduce(lambda x, y: x + y if y % 2 == 0 else x, numbers)
print(sum_even)  # 输出 6

#20. 将列表中的元素进行累加,但只保留大于3的元素:
numbers = [1, 2, 3, 4, 5]
sum_greater_than_3 = reduce(lambda x, y: x + y if y > 3 else x, numbers)
print(sum_greater_than_3)  # 输出 9

  • 10
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值