Python 初学者福音:30个实用任务代码分享

目录

1. 重复元素判定

2. 字符元素组成判定

3. 内存占用

4. 字节占用

5. 打印N次字符串

6. 大写第一个字母

7. 分块

8. 压缩

9. 解包

10. 链式对比

11. 逗号连接

12. 元音统计

13. 首字母小写

14. 展开列表

15. 列表的差

16. 通过函数取差

17. 链式函数调用

18. 检查重复项

19. 合并两个字典

20. 将两个列表转化为字典

21. 反转字符串

22. 斐波那契数列

23. 字符串是否为回文

24. 求最大公约数

25. 将摄氏度转换为华氏度

26. 字符串转为整数

27. 列表元素平方

28. 合并多个字典

29. 列表去重

30. 检查字符串是否只包含数字



学习Python最快的方法就是通过实战。以下是30个极简Python任务,每个任务都有对应的代码片段,帮助你快速掌握Python开发技巧。无论你是初学者还是有经验的开发者,这些代码都能帮你提升技能。

1. 重复元素判定

检查列表中是否存在重复元素,使用set()函数移除重复元素。

def all_unique(lst):
    return len(lst) == len(set(lst))

x = [1, 1, 2, 2, 3, 2, 3, 4, 5, 6]
y = [1, 2, 3, 4, 5]
print(all_unique(x)) # False
print(all_unique(y)) # True

2. 字符元素组成判定

检查两个字符串的组成元素是否一样。

from collections import Counter

def anagram(first, second):
    return Counter(first) == Counter(second)

print(anagram("abcd3", "3acdb")) # True

3. 内存占用

查看变量占用的内存大小。

import sys

variable = 30
print(sys.getsizeof(variable)) # 24

4. 字节占用

检查字符串占用的字节数。

def byte_size(string):
    return len(string.encode('utf-8'))

print(byte_size('')) # 4
print(byte_size('Hello World')) # 11

5. 打印N次字符串

不使用循环语句打印N次字符串。

n = 2
s = "Programming"
print(s * n)
# ProgrammingProgramming

6. 大写第一个字母

使用title()方法大写字符串中每个单词的首字母。

s = "programming is awesome"
print(s.title())
# Programming Is Awesome

7. 分块

按指定大小切割列表。

from math import ceil

def chunk(lst, size):
    return list(map(lambda x: lst[x * size:x * size + size], list(range(0, ceil(len(lst) / size)))))

print(chunk([1, 2, 3, 4, 5], 2))
# [[1, 2], [3, 4], [5]]

8. 压缩

去掉列表中的布尔型值,如False, None, 0, ""。

def compact(lst):
    return list(filter(bool, lst))

print(compact([0, 1, False, 2, '', 3, 'a', 's', 34]))
# [1, 2, 3, 'a', 's', 34]

9. 解包

将打包好的成对列表解开成两组不同的元组。

array = [['a', 'b'], ['c', 'd'], ['e', 'f']]
transposed = zip(*array)
print(list(transposed))
# [('a', 'c', 'e'), ('b', 'd', 'f')]

10. 链式对比

在一行代码中使用不同的运算符对比多个不同的元素。

a = 3
print(2 < a < 8) # True
print(1 == a < 2) # False

11. 逗号连接

将列表连接成单个字符串,元素间用逗号分隔。

hobbies = ["basketball", "football", "swimming"]
print("My hobbies are: " + ", ".join(hobbies))
# My hobbies are: basketball, football, swimming

12. 元音统计

统计字符串中的元音(a, e, i, o, u)个数。

import re

def count_vowels(string):
    return len(re.findall(r'[aeiou]', string, re.IGNORECASE))

print(count_vowels('foobar')) # 3
print(count_vowels('gym')) # 0

13. 首字母小写

将字符串的第一个字符改为小写。

def decapitalize(string):
    return string[:1].lower() + string[1:]

print(decapitalize('FooBar')) # 'fooBar'

14. 展开列表

递归地将嵌套列表展开为单个列表。

def spread(arg):
    ret = []
    for i in arg:
        if isinstance(i, list):
            ret.extend(i)
        else:
            ret.append(i)
    return ret

def deep_flatten(lst):
    result = []
    result.extend(spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst))))
    return result

print(deep_flatten([1, [2], [[3], 4], 5])) # [1, 2, 3, 4, 5]

15. 列表的差

返回第一个列表中不在第二个列表中的元素。

def difference(a, b):
    set_a = set(a)
    set_b = set(b)
    return list(set_a.difference(set_b))

print(difference([1, 2, 3], [1, 2, 4])) # [3]

16. 通过函数取差

应用函数后,返回结果不同的列表元素。

def difference_by(a, b, fn):
    b = set(map(fn, b))
    return [item for item in a if fn(item) not in b]

from math import floor
print(difference_by([2.1, 1.2], [2.3, 3.4], floor)) # [1.2]
print(difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v: v['x']))
# [{ 'x': 2 }]

17. 链式函数调用

在一行代码内调用多个函数。

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

a, b = 4, 5
print((subtract if a > b else add)(a, b)) # 9

18. 检查重复项

检查列表中是否有重复项。

def has_duplicates(lst):
    return len(lst) != len(set(lst))

x = [1, 2, 3, 4, 5, 5]
y = [1, 2, 3, 4, 5]
print(has_duplicates(x)) # True
print(has_duplicates(y)) # False

19. 合并两个字典

合并两个字典。

def merge_two_dicts(a, b):
    c = a.copy() # make a copy of a 
    c.update(b) # modify keys and values of a with the ones from b
    return c

a = {'x': 1, 'y': 2}
b = {'y': 3, 'z': 4}
print(merge_two_dicts(a, b))
# {'x': 1, 'y': 3, 'z': 4}

# 在Python 3.5或更高版本中
def merge_dictionaries(a, b):
    return {**a, **b}

a = { 'x': 1, 'y': 2}
b = { 'y': 3, 'z': 4}
print(merge_dictionaries(a, b))
# {'x': 1, 'y': 3, 'z': 4}

20. 将两个列表转化为字典

将两个列表转化为单个字典。

def to_dictionary(keys, values):
    return dict(zip(keys, values))

keys = ["a", "b", "c"]
values = [2, 3, 4]
print(to_dictionary(keys, values))
# {'a': 2, 'b': 3, 'c': 4}

21. 反转字符串

反转一个字符串。

def reverse_string(s):
    return s[::-1]

print(reverse_string('Hello')) # 'olleH'

22. 斐波那契数列

生成斐波那契数列的前n个数。

def fibonacci(n):
    if n <= 0:
        return []
    elif n == 1:
        return [0]
    elif n == 2:
        return [0, 1]
    else:
        seq = [0, 1]
        while len(seq) < n:
            seq.append(seq[-1] + seq[-2])
        return seq

print(fibonacci(10)) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

23. 字符串是否为回文

检查一个字符串是否为回文。

def is_palindrome(s):
    return s == s[::-1]

print(is_palindrome('racecar')) # True
print(is_palindrome('hello')) # False

24. 求最大公约数

计算两个数的最大公约数。

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

print(gcd(48, 18)) # 6

25. 将摄氏度转换为华氏度

将摄氏温度转换为华氏温度。

def celsius_to_fahrenheit(celsius):
    return (celsius * 9/5) + 32

print(celsius_to_fahrenheit(30)) # 86.0

26. 字符串转为整数

将字符串转换为整数。

def str_to_int(s):
    return int(s)

print(str_to_int('123')) # 123

27. 列表元素平方

返回列表中每个元素的平方。

def square_elements(lst):
    return [x**2 for x in lst]

print(square_elements([1, 2, 3, 4])) # [1, 4, 9, 16]

28. 合并多个字典

合并多个字典。

def merge_multiple_dicts(*dicts):
    result = {}
    for d in dicts:
        result.update(d)
    return result

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict3 = {'d': 5}
print(merge_multiple_dicts(dict1, dict2, dict3))
# {'a': 1, 'b': 3, 'c': 4, 'd': 5}

29. 列表去重

去除列表中的重复元素。

def remove_duplicates(lst):
    return list(set(lst))

print(remove_duplicates([1, 2, 2, 3, 4, 4, 5])) # [1, 2, 3, 4, 5]

30. 检查字符串是否只包含数字

检查字符串是否只包含数字。

def is_numeric(s):
    return s.isdigit()

print(is_numeric('12345')) # True
print(is_numeric('123a5')) # False

通过这些简单的Python代码片段,你可以掌握许多常用的编程技巧和方法。希望这些代码对你的Python学习之旅有所帮助!

  • 9
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

图灵学者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值