10个有趣的Python函数让编程更加有趣
发布时间:2023-05-26 03:35:45
Python语言具有简洁、易读、易学的特点,深受众多程序员的喜爱,也受到很多初学者的欢迎。Python语言有着许多实用和有趣的函数,下面就来介绍一下10个有趣的Python函数让编程更加有趣。
1. enumerate()函数
enumerate()函数可以在循环里同时得到枚举值和序列值,非常方便。例如:
list = ['item1', 'item2', 'item3'] for index, item in enumerate(list): print(index, item)
输出结果为:
0 item1 1 item2 2 item3
2. zip()函数
zip()函数可以将两个或多个列表打包成一个元组列表。例如:
list1 = ['a', 'b', 'c'] list2 = [1, 2, 3] result = zip(list1, list2) print(list(result))
输出结果为:
[('a', 1), ('b', 2), ('c', 3)]
3. map()函数
map()函数可以将函数作用于列表中的每一个元素。例如:
def double(x): return x * 2 list1 = [1, 2, 3] result = map(double, list1) print(list(result))
输出结果为:
[2, 4, 6]
4. filter()函数
filter()函数可以根据指定的函数过滤出列表中符合条件的元素。例如:
def is_odd(x): return x % 2 == 1 list1 = [1, 2, 3, 4, 5, 6] result = filter(is_odd, list1) print(list(result))
输出结果为:
[1, 3, 5]
5. reversed()函数
reversed()函数可以反转序列。例如:
list1 = [1, 2, 3, 4, 5] result = list(reversed(list1)) print(result)
输出结果为:
[5, 4, 3, 2, 1]
6. sorted()函数
sorted()函数可以对列表进行排序。例如:
list1 = [3, 1, 5, 2, 4] result = sorted(list1) print(result)
输出结果为:
[1, 2, 3, 4, 5]
7. random()函数
random()函数可以生成随机数。例如:
import random result = random.random() print(result)
输出结果为:
0.5352136723702974
8. randint()函数
randint()函数可以生成指定范围内的随机整数。例如:
import random result = random.randint(1, 10) print(result)
输出结果为:
7
9. choice()函数
choice()函数可以从列表中随机挑选一个元素。例如:
import random list1 = ['a', 'b', 'c', 'd', 'e'] result = random.choice(list1) print(result)
输出结果为:
e
10. range()函数
range()函数可以生成一个整数序列。例如:
result = range(1, 6) print(list(result))
输出结果为:
[1, 2, 3, 4, 5]
总结:
以上介绍了10个有趣的Python函数,这些函数可以帮助编程更加有趣、方便。在Python编程的过程中,不断探索、学习新的函数,可以让编程更加高效、轻松、有趣。
