python简短实例

2022/6/12 1:20:28

本文主要是介绍python简短实例,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

#重复元素判定
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))
print(all_unique(y))
False
True
#字符元素组成判定,两个字符串组成元素是否一样
from collections import Counter

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

anagram("abcd3","3acbd")

True
#内存占用

import sys
variable = 30
print(sys.getsizeof(variable))

28
#字节占用
def byte_size(string):
    return len(string.encode('utf-8'))


byte_size('Hello World')
11
#打印N次字符串

n = 2
s ="Programing"
print(s*n)

ProgramingPrograming
#给定具体大小,定义一个函数以按照这个大小切割列表
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)))))

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

[[1, 2], [3, 4], [5]]
#压缩
def compact(lst):
    return list(filter(bool,lst))

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

[1, 2, 3, 'a', 's', 34]
#解包 unsuccessful
array = [['a','b'],['c','d'],['e','f']]
transposed = zip(*array)

print(transposed)
<zip object at 0x00000172C944E6C0>
#链式对比
a =3
print(2<a<8)
True
#逗号链接
hobbies = ["basketball","football","swimming"]
print("My hobbies are:"+",".join(hobbies))
My hobbies are:basketball,football,swimming
#元音统计  (aeiou) 通过正则表达式
import re

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

count_vowels('foobar')
3
def count_vowels(str):
    return re.findall(r'[aeiou]',str,re.IGNORECASE)

count_vowels('foobar')
['o', 'o', 'a']
#展开列表 通过递归方式将列表嵌套展开为单个列表

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


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

[1, 2, 3, 4, 5]
#列表的差
def difference(a,b):
    set_a = set(a)
    set_b = set(b)
    comparison = set_a.difference(set_b) #a有b无
    return list(comparison)

difference([1,2,3],[1,2,4])
[3]
#链式函数调用
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
#合并两个字典
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}
#使用枚举  通常用for循环,但也能枚举列表的索引与值

list = ['a','b','c','d']
for index, element in enumerate(list):
    print('Value',element,'Index',index)

Value a Index 0
Value b Index 1
Value c Index 2
Value d Index 3
#try else
try:
    2*3
except TypeError:
    print("An exception was raised")
else:print("Thank God, no exceptions were raised.")
Thank God, no exceptions were raised.
#元素频率
def most_frequent(list):
    return max(set(list),key=list.count) # 传入count函数之后,再set,再max取最多

list = [1,2,1,2,3,2,1,4,2]
most_frequent(list)
2
#回文序列
from re import sub
def palindrome(string):
    subs = sub('[\W_]', '', string.lower())
    return subs == subs[::-1]

palindrome('taco caT')
True
#不使用if-else就实现加减乘除,求幂操作. 它通过字典这一数据结构实现:

import operator
action = {"+":operator.add,"-":operator.sub,"/":
    operator.truediv,"*":operator.mul,"**":pow}

print(action['-'](50,25))
25
#交换值
def swap(a,b):
    return b,a
a,b=-1,14
swap(a,b)
(14, -1)
#字典默认值
d={'a':1,'b':2}
print(d.get('c',3))
3
#展开列表
def spread(arg):
    ret =[]
    for i in arg:
        if isinstance(i, list):
            ret.extend(i)
        else:
            ret.append(i)
    return ret

spread([1,2,3,[4,5,6],[7],8,9])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
def most_frequent(lst):
    return max(set(lst),key=lst.count)

lst = [1,2,1,2,3,2,1,4,2]
most_frequent(lst)
2
#恢复关键字变量原有含义
from pydoc import locate
list = locate('list')


这篇关于python简短实例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程