首页 > 编程语言 >15个python小例子助你快速回忆python

15个python小例子助你快速回忆python

时间:2023-01-18 17:46:04浏览次数:38  
标签:love python list1 Python Str print 15 回忆

# -*- coding: utf-8 -*-
"""
====================================
@File Name :20个小知识.py
@Time : 2023/1/17 17:59
@Program IDE :PyCharm
@Create by Author : 一一吴XX
@Motto:"The trick, William Potter, is not minding that it hurts."
====================================
"""
import random
import re
from iteration_utilities import deepflatten
"""
1.字符串的翻转
"""
Str = "Hello World"
print(Str[::-1])   # dlroW olleH

"""
2.单词大小写
"""
Str = "i love python"
print(Str.title())   # I Love Python 单词首字母大写
print(Str.upper())   # I LOVE PYTHON   所有字母大写
print(Str.capitalize()) # I love python 字符串首字母大写


"""
3.字符串拆分
"""
Str1 = "I love Python"
Str2 = "I/love/Python"
Str3 = "   I love Python   "

print(Str.split())  # ['i', 'love', 'python'] 空格进行拆分,返回的是列表
print(Str2.split('/'))    # ['I', 'love', 'Python']
print(Str3.strip())  #I love Python  默认去除字符串的2边空格
print(type(Str3.strip()))  #<class 'str'>  输出类型

"""
4.列表中的字符串合并
"""
list1 = ["I","love","Python"]
print(' '.join(list1))   # I love Python

"""
5.去除字符串中不需要的字符
"""
Str = "I/ love. python"
print(' '.join(re.split('\W+',Str)) ) # \W 表示除英文字母以外的

"""
6.寻找字符串中唯一的元素
"""
Str = "wwweeerfttttg"
print(''.join(set(Str)))   #grfwte

list1 = [2,5,6,5,5,6,2]
print(list(set(list1)))  #[2, 5, 6]

"""
7.将元素进行重复
"""
Str = "python"
print(Str * 2)   # pythonpython
list1 = [1,2,3]
print(list1 * 2)  # [1, 2, 3, 1, 2, 3]

'''或者用 + 处理'''
Str1 = ""
list12 = []
for i in range(2):
   Str1 += Str
   list12.extend(list1)

print(Str1)
print(list12)

"""
8.基于列表的扩展
"""
list13 = [2,2,2,2]
print([2 * x for x in list13])   # [4, 4, 4, 4]

list14 = [[1,2,3],[4,5,6],[7,8,9]]
print([i for k in list14 for i in k])  #    [1, 2, 3, 4, 5, 6, 7, 8, 9] 等同于 php的 array_reduce($a,'array_merge',[])

list15 = [[1,2,3],[4,5,6],[7,8,9]]
print(list(deepflatten(list15)))  #[1, 2, 3, 4, 5, 6, 7, 8, 9]   不知道嵌套深度使用


list16 = [[1,2,3],[4,5,6],[7,[8,9]]]
print(list(deepflatten(list15)))   #[1, 2, 3, 4, 5, 6, 7, 8, 9]

"""
9.统计列表中元素的频率
"""
from collections import Counter
list17 = [1,1,1,2,3,3,4,5,6,6]
count = Counter(list17)
print(count)   # Counter({1: 3, 3: 2, 6: 2, 2: 1, 4: 1, 5: 1})
print(count[1])  # 得到1出现的频率是 3

#手动实现
dict1 = {}
for i in list17:
   if i in dict1:
      dict1[i] += 1
   else:
      dict1[i] = 1

print(max(dict1,key = lambda x:dict1[x]))


"""
10 判断字符串所含元素是否相同
"""
Str1,Str2,Str3 = "qwet","qwet","tewq"
if Counter(Str1) == Counter(Str2) and Counter(Str2) == Counter(Str3):
   print("元素相同")
else:
   print("元素不相同")

"""
11 将数字字符串转化为数字列表
"""

Str = "123456789"
print([int(i) for i in Str])  #[1, 2, 3, 4, 5, 6, 7, 8, 9]
#或者
print(list(map(int,Str)))

"""
12 使用try-except-finally模块
"""
a = 1
b = 4
try:
   a.append(b)
except AttributeError as e:
   print(e)
else:
   print(a)
finally:
   print("执行完毕")

"""
13 使用enumerate() 函数来获取索引-数值对
"""
Str = "python"
for i in enumerate(Str):
   print(i)

"""
输出
(0, 'p')
(1, 'y')
(2, 't')
(3, 'h')
(4, 'o')
(5, 'n')

"""
C1 = [1,2,3,4,5]
for i in enumerate(C1):
   print(i)

"""
输出
(0, 1)
(1, 2)
(2, 3)
(3, 4)
(4, 5)
"""

"""
13 字典的合并
"""
a = {
   "a":1,
   "b":2
}
b = {
   "c":3,
   "d":4
}

#方法1
combine = {** a,** b}
print(combine)   #{'a': 1, 'b': 2, 'c': 3, 'd': 4}
#方法2
a.update(b)
print(a)   # {'a': 1, 'b': 2, 'c': 3, 'd': 4}

"""
14 随机采样
"""
a = "jdkosjodifjs"
b = [1,2,3,4,5,6]
print(random.sample(a,3))  #['d', 'f', 'j']
print(random.sample(b,3))  #[1, 3, 5]

"""
15 检查唯一性
"""
a = [1,2,3,4,4]
if len(list(set(a))) == len(a):
   print("元素唯一")
else:
   print("元素不唯一")

  

标签:love,python,list1,Python,Str,print,15,回忆
From: https://www.cnblogs.com/wujf-myblog/p/17060299.html

相关文章

  • Python基础之函数
    目录Python基础之函数一、函数相关的基础知识1.函数的语法结构2.函数的定义与调用3.函数的分类4.函数的返回值5.函数的参数6.名称空间7.名字的查找顺序以及实际案例8.globa......
  • Servlet15 - 实现模糊查询
    模糊查询在首页添加支持模糊查询的输入框模糊查询的表单提交请求使用的是post方法,因为需要传给服务器查询关键字查询结果跳转页面还是首页,只需要在IndexServlet中重......
  • python os模块总结
    os(operatingsystem)是python标准库中的操作系统接口,提供了很多与操作系统进行交互的函数。下面我将在C:\Users\Administrator\try这一路径下执行test.py来详细说明os的......
  • ts15属性的封装
    (function(){//定义一个表示人的类classPerson{/*可以在属性前面添加属性的修饰符public:public修饰的属性可以在任意部分访......
  • python pathlib.Path 路径拼接
    frompathlibimportPatha=Path(r'E:\python_apps\bk-pipline\x52_merge_workspace\time_flush\client\3droom\A-1.17.0.xml')b=Path(r'E:\python_apps\bk-pipline\x......
  • python的assert和raise的用法
    一、raise用法在程序运行的过程当中,除了python自动触发的异常外,python也允许我们在程序中手动设置异常,使用raise语句即可,为什么还要手动设置异常呢?首先要分清楚程序发......
  • Python文件操作基础方法
    importosimportshutil#创建文件defCreateFile(filename):f=open(filename,mode='a',encoding='utf-8')f.close()print("-------文件创建成功------......
  • linux系统中更新python
    Linux系统中更新Python首先到Python的Ftp服务器上(https://www.python.org/ftp/python/),找到你喜欢的版本的Python。我选择的就是3.11.1版本的Python。在Linux服务......
  • 数据类型python
    type()语句的用法运行结果......
  • python 类与对象
    python类与对象(未完待续)类定义括号里的是继承类,如果没有类继承,就继承object类,它是所有类的基础类。pass是占位符,还可用在判断和循环中class类名(object):pa......