Python函数编程实例:10个实用的代码片段
发布时间:2023-05-29 04:51:54
Python作为一门优雅、简洁、功能强大的语言,越来越受到人们的喜爱。其中函数式编程的风格越来越受到开发者的青睐。本文提供了10个实用的Python函数编程的代码片段。
1. 对列表元素进行某种操作
numbers = [1, 2, 3, 4, 5] new_numbers = list(map(lambda x: x * x, numbers)) print(new_numbers)
2. 将序列分组成指定大小的块
from itertools import zip_longest
def grouper(iterable, size):
args = [iter(iterable)] * size
return zip_longest(*args)
list1 = list(range(10))
group_size = 4
groups = grouper(list1, group_size)
for group in groups:
print(list(group))
3. 判断是否为真
print(bool(0)) # False
print(bool(None)) # False
print(bool("")) # False
print(bool([])) # False
print(bool({})) # False
4. 对字典根据值进行排序
d = {"A": 5, "B": 2, "C": 9, "D": 1}
sorted_dict = dict(sorted(d.items(), key=lambda x: x[1]))
print(sorted_dict)
5. 扁平化嵌套的列表
def flatten(lst):
for sublist in lst:
if isinstance(sublist, list):
yield from flatten(sublist)
else:
yield sublist
original_list = [[1, 2, 3], [4, [5, 6]], [7, 8, 9]]
flattened_list = list(flatten(original_list))
print(flattened_list)
6. 计算多个列表元素的交集
list1 = [1, 2, 3, 4] list2 = [2, 4, 6, 8] list3 = [3, 4, 5, 6] common_elements = set(list1).intersection(list2, list3) print(common_elements)
7. 链式函数调用
class Chainable:
def __init__(self, value):
self.value = value
def fn1(self):
self.value += 1
return self
def fn2(self):
self.value *= 2
return self
c1 = Chainable(3)
c2 = c1.fn1().fn2().fn1()
print(c2.value)
8. 统计某个字符在字符串中出现的次数
def count_in_string(string, char):
return len(list(filter(lambda c: c == char, string)))
s = "Hello World"
c = "l"
count = count_in_string(s, c)
print(count)
9. 反转字符串的单词顺序
def reverse_words(string):
return " ".join(reversed(string.split()))
s = "Hello World"
reverse_s = reverse_words(s)
print(reverse_s)
10. 比较两个字符串是否为同一字母异序词
def is_anagram(s1, s2):
s1_chars = list(s1)
s1_chars.sort()
s2_chars = list(s2)
s2_chars.sort()
return s1_chars == s2_chars
s1 = "hello"
s2 = "lloeh"
print(is_anagram(s1, s2)) # True
以上就是10个实用的Python函数编程的代码片段。通过使用这些代码片段和思想,可以让我们编写出更加优美、高效且易于维护的代码。
