python笔记

输出格式

a=30
b=20
print('hello world:',a,'+',b,'=',a+b)
print('hello world:%d+%d=%d'%(a,b,a+b))
print('hello world:{0}+{1}={2}'.format(a,b,a+b ))
print(f'hello world:{a}+{b}={a+b}')
a = 1.2345
b = 2.3456
print('hello world:', "{:.2f}".format(a), '+', "{:.2f}".format(b), '=', "{:.2f}".format(a + b))
print('hello world:%0.2f+%0.2f=%0.2f' % (a, b, a + b))
print('hello world:{0:.2f}+{1:.2f}={2:.2f}'.format(a, b, a + b))
print(f'hello world:{a:.2f}+{b:.2f}={a + b:.2f}')
a=3.1415926
b='重庆理工大学'
print("@%f# @%9.2f#, @%.2f#, @%9.2f#, @%10s#"%(a,a,a,a,b))
print("%9.2f"%(a),end=",")
print("{0:9.2f}".format(a),end=",")
print(f"{a:9.2f}")
print(f"假设π的值为{a:.2f},那么 2π的值为{2*a:.2f}。")

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

 import math            #这种导入方式,后续必须使用"math
 from math import * #可以不用"math."
import math
a,b,c=0.1,0.2,0.3 #拆包赋值
print(a+b) #结果为:0.30000000000000004
print(a+b==c) #结果为:False
print(math.fabs(a+b-c)<1e-6) #结果为:True
print(math.isclose(a+b,c)) #结果为:True
print(math.isclose(a+b-c,0)) #结果为:False,该函数第二个参数最好不要为0

浮点数有精度损失

round(y,2)#保留小数
str='python Book'
 # 全部大写:str.upper()
 # 全部小写:str.lower()
 # 大小写互换:str.swapcase()
 # 首字母大写,其余小写:str.capitalize()
 # 首字母大写:str.title()
str='python Book'
# 字符串搜索相关
# 搜索指定字符串,没有返回-1:str.find('t')
# 指定起始位置搜索:str.find('t',start)
# 指定起始及结束位置搜索:str.find('t',start,end)。,start闭区间,end是)开区间
# 从右边开始查找:str.rfind('t')
# 搜索到多少个指定字符串:str.count('t')
# 上面所有方法都可用index代替,不同的是使用index查找不到会抛异常,而find返回-1
# 替换old为new:str.replace('old','new')
# 替换指定次数的old为new:str.replace('old','new',maxReplaceTimes)
# 字符串去空格及去指定字符
# 去两边空格:str.strip()
# 去左空格:str.lstrip()
# 去右空格:str.rstrip()
# 去两边字符串:str.strip('d'),相应的也有lstrip,rstrip
是存在字符串就去掉
# 按指定字符分割字符串为数组:str.split(' ')
# 字符串判断相关
# 是否以start开头:str.startswith('start')
# 是否以end结尾:str.endswith('end')
# 是否全为字母或数字:str.isalnum()
# 是否全字母:str.isalpha()
# 是否全数字:str.isdigit()
# 是否全小写:str.islower()
# 是否全大写:str.isupper()
'3423'.isdigit()
# 格式化相关,对齐,指定宽度
# 右对齐,左边不够用空格补齐:str.ljust(width)
# 左对齐,右边不够用空格补齐:str.rjust(width)
# 中间对齐,两边不够用空格补齐:str.center(width)
# 右对齐,左边不足用0补齐:str.zfill(width)
s='abcd'
print("'abcd'.ljust(10)='{}'".format(s.ljust(10)))
print("'abcd'.rjust(10)='{}'".format(s.rjust(10)))
print("'abcd'.center(10)='{}'".format(s.center(10)))
print("'abcd'.zfill(10)='{}'".format(s.zfill(10)))

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

左对齐

s = "Hello"
new_s = "{:<10}".format(s)
print(new_s)  
# 输出:Hello     
new_s = "{:*<10}".format(s)
print(new_s)  
# 输出:Hello*****

计数函数counter

找出签到数据中重复签到的同学

输入格式:

[1, 2, 2, 3, 4, 5, 4],数字表示收集的签到的学生的学号

输出格式:

2 4
输出重复签到的学生学号,从小到大输出,数字后面有一个空格符

from collections import Counter
#13 3 2 -1 5 3 4 3 0 3 2 12 3 123
#dict_items([(13, 1), (3, 5), (2, 2), (-1, 1), (5, 1), (4, 1), (0, 1), (12, 1), (123, 1)])
def find_duplicates(sign_in_data):
    count = Counter(sign_in_data)
    duplicates = sorted([num for num, freq in count.items() if freq > 1])
    print(" ".join(map(str, duplicates)) + " ")

sign_in_data = [int(x) for x in input().strip('[]').split(', ')]

find_duplicates(sign_in_data)

判断大小写数字

	if char.islower():
            has_lowercase = True
        elif char.isupper():
            has_uppercase = True
        elif char.isdigit():
            has_digit = True
        else:
            has_other = True
for i, num in enumerate(nums):
#zip配对  (('A', 'Z'), ('B', 'Y')-------)
transform_table = tuple(zip("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "ZYXWVUTSRQPONMLKJIHGFEDCBA"))
#lst1 = [22, 2],lst2 = [1, 11]
lst3 = zip(lst1, lst2)
for i in lst3:
    print(i)
#(22, 1)    (2, 11)
for i,j in zip(list1,list2):
#strip() 是字符串对象的一个方法,用于去除字符串前后的空格(包括空格、制表符 \t、换行符 \n 等)
sign_in_data = [int(x) for x in input().strip('[]').split(', ')]
#列表、元组、字典输入都可用
list1 = eval(input())
list=list(set(eval(input())))
list.sort(reverse=True)
#str连接
s = " ".join(my_list) #str
print(" ".join(my_list))
#Counter
from collections import Counter
count = Counter(sign_in_data)
#[1,2,3]->1 2 3
print(*unique_lst)
#返回不小于 s 的最小整数,向上取整
math.ceil(s)
#矩阵
n = int(input())
matrix = []
for _ in range(n):
    row = list(map(float, input().split()))
    matrix.append(row)
print(matrix)
#逆序
for index in range(len(nums) - 1, -1, -1):
#字典 key()  value()  items()
#排序lambda
sorted_courses = sorted(scores.items(), key=lambda x: x[1], reverse=True)
ll = sorted(l.items(), key=lambda x: (-x[2], x[1], x[0]))
old.sort(key=lambda x: x[1], reverse=True)
sorted_words = sorted(word_dict.items(), key=lambda item: (-item[1], item[0]))
#删除列表  my_list = [10, 20, 30, 40] --->[10,30,40]
del my_list[1]
#count
most_common_occupation = max(set(occupations), key=occupations.count)
#capitalize() 是字符串对象的一个方法,它会将字符串的第一个字符转换为大写,而将其余字符转换为小写
country = input().capitalize()
from collections import Counter

occupations = ['teacher', 'doctor', 'teacher', 'engineer', 'teacher']
#Counter   [('teacher', 3)]
counter = Counter(occupations)
most_common_occupation = counter.most_common(1)[0][0]
#count
most_common_occupation = max(set(occupations), key=occupations.count)
#print执行
nums = [1, 2, 3,4, 5]
for num in nums:
    print(num)
else:
    print("循环正常结束,没有执行break")
#回文
def isPalindrome(str):
    reversed_str = str[::-1]
    return str == reversed_str

冒泡排序

def bubble_sort(lst):
    n = len(lst)
    for i in range(n):
        for j in range(0, n - i - 1):
            if lst[j]>lst[j + 1]:
                # 交换元素位置
                lst[j], lst[j + 1]=lst[j + 1], lst[j]
    return lst

选择排序

def selection_sort(lst):
    n = len(lst)
    for i in range(n):
        min_idx = i
        for j in range(i + 1, n):
            if lst[j]<lst[min_idx]:
                min_idx = j
        # 交换元素
        lst[i], lst[min_idx]=lst[min_idx], lst[i]
    return lst

插入排序

n=len(lst)
for i in range(1, n):
    for j in range(i, 0, -1):
        if lst[j] <= lst[j - 1]:
            lst[j], lst[j - 1] = lst[j - 1], lst[j]
print(lst)

快速排序

def quick_sort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr) // 2]  # 选择基准点,可以是中间元素
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]

    return quick_sort(left) + middle + quick_sort(right)

sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2] # 选择基准点,可以是中间元素
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]

return quick_sort(left) + middle + quick_sort(right)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值