本篇文章将会展示一些常见的函数,并利用一行代码完成一项任务!
>>> squares = [x**2 for x in range(1, 21)] # 生成1~20的平方数
>>> squares
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]
>>> odd_numbers = [x for x in range(1, 21) if x % 2 == 1] # 筛选1~20之间的奇数
>>> odd_numbers
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> words = ["Hello ", "I", "a M", " Tony "]
>>> lower_words = [word.lower().strip() for word in words] # 字母转为小写并去除前后空格
>>> lower_words
['hello', 'i', 'a m', 'tony']
>>> square = lambda x: x**2 # 计算平方
>>> square
<function <lambda> at 0x0000019E407CF920>
>>> is_odd = lambda x: x % 2 == 1 # 检查是否为奇数
>>> is_odd
<function <lambda> at 0x0000019E407CF7E0>
>>> odd_numbers = list(filter(lambda x: x % 2 == 1, [x for x in range(1, 21)])) # 筛选1~20之间的奇数
>>> odd_numbers
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> squares = list(map(lambda x: x**2, [x for x in range(1, 21)])) # 生成1~20的平方数
>>> squares
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]
>>> odd_or_even = "odd" if 2023 % 2 == 1 else "even" # 判断2023是奇数还是偶数
>>> odd_or_even
'odd'
>>> keys = ["name", "age"]
>>> values = ["小邓在森林", 21]
>>> mydict = dict(zip(keys, values)) # 将两个列表合并为字典
>>> mydict
{'name': '小邓在森林', 'age': 21}
>>> letters = ['a', 'b', 'c', 'd', 'e']
>>> for index, letter in enumerate(letters): # 获取列表元素及其索引
... print(f"Index: {index}, Letter: {letter}")
...
Index: 0, Letter: a
Index: 1, Letter: b
Index: 2, Letter: c
Index: 3, Letter: d
Index: 4, Letter: e
先在编写的代码目录下创建 test.txt
文件,文件内容如下:
我是小邓在森林
这是我的test.txt文件!
读取文件内容:
>>> lines = [line.strip() for line in open("test.txt")] # 读取文件所有行
>>> lines
['我是小邓在森林', '这是我的test.txt文件!']
向文件内写入内容:
>>> with open("test.txt", "w") as f:
... f.write("我来自中国!")
...
>>> lines = [line.strip() for line in open("test.txt")] # 读取文件所有行
>>> lines # 由于在写入时使用了w,表示创建或者清空文件再写入内容
['我来自中国!']
>>> with open("test.txt", "a") as f: # 尝试用a:追加内容模型,不清空内容,直接在文末添加
... f.write("我是小邓在森林~")
...
>>> lines = [line.strip() for line in open("test.txt")] # 读取文件所有行
>>> lines
['我来自中国!我是小邓在森林~']
>>> squares_dict = {x: x**2 for x in range(1, 21)} # 将列表元素作为键,平方作为值构建字典
>>> squares_dict
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225, 16: 256, 17: 289, 18: 324, 19: 361, 20: 400}
>>> filtered_dict = {key: value for key, value in squares_dict.items() if value < 10} # 筛选字典中值小于10的项
>>> filtered_dict
{1: 1, 2: 4, 3: 9}