老司机都知道的Python语法小技巧 (一)

  • 话不多说,本文是第一部分,将讲简单的列出几条日常工作中使用Python可能会用到的语法小技巧,希望会对你的工作有所帮助 just enjoy!

本文首发于伊洛的个人博客:https://yiluotalk.com,欢迎关注并查看更多内容!!!

1. 两个变量直接做交换
# 伊洛Yiluo
# https://yiluotalk.com
>>> num1 = 6
>>> num2 = 10
>>> num1, num2 = num2, num1
>>> num1
10
>>> num2
6
2. 检查数字是否为偶数
# 伊洛Yiluo
# https://yiluotalk.com
>>> def is_even(num):
...     return num %2 == 0
...
>>> is_even(100)
True
>>> is_even(99)
False
3. 字符串拆为列表
# 伊洛Yiluo
# https://yiluotalk.com
def split_lines(s):
    return s.split('/n')


talk = 'The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex.'

print(split_lines(talk))


output
['The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex.']

Process finished with exit code 0

4. 查找对象内存
# 伊洛Yiluo
# https://yiluotalk.com
>>> import sys
>>> sys.getsizeof(5)
28
>>> print(sys.getsizeof("Python"))
55
5. 反转字符串
# 伊洛Yiluo
# https://yiluotalk.com
>>> string = "python"
>>> reversed_string = string[::-1]
>>> reversed_string
'nohtyp'
6. 打印一个字符串n次(不用循环)
# 伊洛Yiluo
# https://yiluotalk.com
>>> def repeat(string, n):
...     return (string * n)
...
>>> repeat('hello', 8)
'hellohellohellohellohellohellohellohello'
7.判断字符串是否回文
# 伊洛Yiluo
# https://yiluotalk.com
>>> def palindrome(string):
...     return string == string[::-1]
...
>>> palindrome('python')
False
>>> palindrome('abba')
True
8. 将字符串列表合并为一个字符串
# 伊洛Yiluo
# https://yiluotalk.com
>>> strings = ['yiluo', 'hello', '18']
>>> print(','.join(strings))
yiluo,hello,18
>>> a = (','.join(strings))
>>> a
'yiluo,hello,18'
>>> type(a)
<class 'str'>
9. 查找列表的第一个元素
# 伊洛Yiluo
# https://yiluotalk.com
>>> def head(list):
...     return list[0]
...
>>> head(['yiluo','tom', 1, 2])
'yiluo'
10.合并两个列表中共有的元素
# 伊洛Yiluo
# https://yiluotalk.com
>>> def union(a, b):
...     return list(set(a + b))
...
>>> union([1,2,3,4,5,6], [6,5,4,3])
[1, 2, 3, 4, 5, 6]
>>> union([1,2,3,4,5,6], [8,7,6,5,4,3,2,1])
[1, 2, 3, 4, 5, 6, 7, 8]
11. 给定列表中所有唯一元素
# 伊洛Yiluo
# https://yiluotalk.com
>>> def unique_element(numbers):
...     return list(set(numbers))
...
>>> unique_element([1,1,2,2,3,3,4,4,5,5])
[1, 2, 3, 4, 5]
12. 多参数平均值
# 伊洛Yiluo
# https://yiluotalk.com
>>> def average(*args):
...     return sum(args, 0.0) / len(args)
...
>>> average(2,4)
3.0
>>> average(2,4,6,8)
5.0
13. 检查列表元素是否唯一
# 伊洛Yiluo
# https://yiluotalk.com
>>> def unique(list):
...     if len(list)==len(set(list)):
...         print('都是唯一的')
...     else:
...         print('很不幸,有重复的')
...
>>> unique([1,2,3,4,5])
都是唯一的
>>> unique([1,1,2,2,3,3,4,4,5,5])
很不幸,有重复的
待续>>>

欢迎下方【戳一下】【点赞】
Author:伊洛Yiluo
愿你享受每一天,Just Enjoy !

关注公众号获取更多内容