python学习笔记1

常用保留字
import keyword keyword.kwlist

python // 为取整除,向下取整接近商的整数 / 除,例如b除以a 1<2==2 等同于(1<2)and(2==) san = a if a<b else b #替代三元运算符 num1,num2=2,4 #多个变量赋值
not (4==6) and 5+7/2 or 0
都是True的情况下and会返回后一个,or会返回前一个。 都是False的情况下and会返回前一个,or会返回后一个。 前面是True后面是False情况下and会返回后一个,or会返回前一个。 前面是False后面是True情况下and会返回前一个,or会返回后一个。 大体就是and一遇到False立马返回,or一遇到True立马返回。

is和==的区别
is判断a对象是否就是b对象,用于判断两个变量引用对象是否为同一个,是通过id来判断的 ==判断a对象的值是否和b对象的值相等,是通过value来判断的

列表、元组、集合、字典的区别
列表(list):是长度可变有序的数据存储容器,可以通过下标索引取到相应的数据 元组(tuple):固定长度不可变的顺序容器,访问效率高,适合存储一些常量数据,可以作为字典的键使用 集合(set):无序,元素只出现一次,可以自动去重 字典(dict):长度可变的hash字典容器。存储的方式为键值对,可以通过相应的键获取相应的值,key支持多种类型。key必须是不可变类型且唯一

内置函数
练习:
去除a = " heheheh ",请去除尾部
a = " heheheh " a.rstrip()

字符串的查询替换使用哪两个函数
使用find和replace函数 find函数返回值为0或正数时,为其索引号 replace 将short替换成long

判断一个字符串是否全为数字
1)isdigit()方法检测字符串中是否只有数字
str_one = '123456' str_two = 'no numbers!' print(str_one.isdigit(),str_two.isdigit())

  1. isnumeric()方法检测字符串是否只由数字组成。这种方式只针对Unicode字符串。如果想定义一个字符串为Unicode,那么只需要在字符串前添加'u'前缀即可

str_three = u'python2021' print(str_three.isnumeric()) str_four = u'2021325' print(str_four.isnumeric())

  1. 自定义is_number来判断
def is_number(s):
  try:
    flaot(s)
    return Ture
  except ValueError:
    pass
  try:
    import unicodedata
    unicodedata.numeric(s)
    return True
  except(TypeError,ValueError):
    pass
  return False

测试字符串和数字
print(is_number('foo'))
print(is_number('123'))

字典中的内置函数

在列表中输入多个数据作为圆的半径,得出圆的面积

import math
a = [5,10,15]

for i in a:
    c = math.pi*math.pow(i,2)
    print(c)

import math
a = [5,10,15]
print([math.pi*math.pow(x,2) for x in a])



判断dict是否包含某个key的方法是什么
in
字典d = {'a':1,'b':2,'c':3},请打印出键值对

dic = {'name':'mtcx','age',24},请用pop和del删除字典中name字段

dic = {'name':'mtcx','age':24}
dic.pop('name')
print(dic)

dic = {'name':'mtcx','age':24}
del dic['name']
print(dic)

字典中items()方法与iteritems()方法有什么不同

字典是python语言中唯一的映射类型。映射类型对象里哈希键(键,key)和指向的对象(值,value)是多对一的关系,通常被认为是可变的哈希表。字典对象是可变的,他是一个容器类型,能存储任意个数的python对象,其中也可包括其他容器类型。
字典是一种可变容器模型,且可存储任意类型对象。字典的每个键值(key=>value)对用冒号(:)分隔,每个对之间用逗号(,)分割,整个字典包括在花括号({})中。

d = {key1:value1,key2:value2}
键必须是唯一的,但值则不必唯一。值可以取任何数据类型,但键必须是不可变的,例如字符串、元组和数字

集合中常见的内置方法

|  add(...)
|      Add an element to a set.
|      This has no effect if the element is already present.
|  clear(...)
|      Remove all elements from this set.
|  copy(...)
|      Return a shallow copy of a set.
|  difference(...)
|      Return the difference of two or more sets as a new set.
|      (i.e. all elements that are in this set but not the others.)
|  difference_update(...)
|      Remove all elements of another set from this set.
|  discard(...)
|      Remove an element from a set if it is a member.
|      If the element is not a member, do nothing.
|  intersection(...)
|      Return the intersection of two sets as a new set.
|      (i.e. all elements that are in both sets.)
|  intersection_update(...)
|      Update a set with the intersection of itself and another.
|  isdisjoint(...)
|      Return True if two sets have a null intersection.
|  issubset(...)
|      Report whether another set contains this set.
|  issuperset(...)
|      Report whether this set contains another set.
|  pop(...)
|      Remove and return an arbitrary set element.
|      Raises KeyError if the set is empty.
|  remove(...)
|      Remove an element from a set; it must be a member.
|      If the element is not a member, raise a KeyError.
|  symmetric_difference(...)
|      Return the symmetric difference of two sets as a new set.
|      (i.e. all elements that are in exactly one of the sets.)
|  symmetric_difference_update(...)
|      Update a set with the symmetric difference of itself and another.
|  union(...)
|      Return the union of sets as a new set.
|      (i.e. all elements that are in either set.)
|  update(...)
|      Update a set with the union of itself and others.

在列表str_list=['a','b','c',4,'b',2,'a','c',1,1,3]中求只出现一次的第一次出现的字符

利用count函数

给定两个列表,如何找出他们相同的元素和不同的元素
使用集合操作

list_one = [1,2,3]
list_two = [3,4,5]
set_one = set(list_one)
set_two = set(list_two)
print(set_one&set_two)
print(set_one^set_two)


请将"1,2,3"变成['1','2','3']
python中字符串的split()方法可以通过指定分隔符对字符串进行切片,如果参数num有指定值,那么分隔num+1个子字符串。所以可以使用split方法

那么把['1','2','3']变为[1,2,3]呢

s1 = "1,2,3"
s2 = list(s1.split(','))
s3 = list(map(int,s2))
print(s2,'\n',s3)

将字符串:"k1:1|k2:2|k3:3|k4:4",处理成python字典:{'k1': '1', 'k2': '2', 'k3': '3', 'k4': '4'}
可以通过对字符串进行切片来实现

str_first = "k1:1|k2:2|k3:3|k4:4"
def str2dict(str1):
    dict1 = {}
    for items in str1.split("|"):
        key,value = items.split(':')
        dict1[key] = value
    return dict1

print(str2dict(str_first))

L = range(100),取第一到第三个元素用L[:3]、取倒数第二个元素L[-2]、取后十个元素L[-10]

有如下数组li = list(range(10)),若想取以下几个数组,则应该如何切片

[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6]
[3, 4, 5, 6]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
[1, 3, 5, 7, 9]
[9, 8, 7, 6, 5, 4, 3, 2]
[8, 9]

如何判断一个字符串是否为回文字符串
回文字符串就是一个正着读和反着读都一样的字符串,例如“level”或者“noon”等

def converted(s):
    ss = s[:]
    if len(ss) >= 2 and s == s[::-1]:
        return True
    else:
        return False

if __name__ == "__main__":
    s = "abcdcba"
    print(converted(s))    #True
    print(converted("adgede"))  #False

请输入3个数字,以逗号隔开,输出其中最大的数

def findMaxNum(x,y,z):
    if x < y:
        x,y = y,z
    if x < z:
        x,z = z,x
    return x

if __name__ == "__main__":
    numList = input("please enter three numbers,Separated by commas:").split(',')
    print(numList)  #['1', '2', '3']
    res = findMaxNum(int(numList[0]),int(numList[1]),int(numList[2]))
    print(res)      #3

求两个正整数m和n的最大公约数
最大公约数,也称最大公因数、最大公因子,是指两个或多个整数共有约束中最大的一个

a,b = "64,24".split(',')
a,b = int(a),int(b)
c = a % b
while c:
    a,b = b,c
    c = a % b

print(b)  #8

求两个正整数的最小公倍数
两个或多个整数共有的倍数叫做它们的公倍数,其中除0以外最小的一个公倍数就叫这几个整数的最小公倍数。

#最小公倍数
def lcm(x,y):
    #获取最大数
    if x > y:
        greater = x
    else:
        greater = y

    while(True):
        if((greater % x == 0) and (greater % y == 0)):
            lcm = greater
            break
        greater += 1

    return lcm

#获取用户输入
num1 = int(input("please enter first number:"))
num2 = int(input("please enter second number:"))
print("The least common multiple of",num1,'and',num2,"is",lcm(num1,num2))

一个列表a=[2,3,4],将其转换为[(2, 3), (3, 4), (4, 2)]
image
写出A0、A1至An的值

A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))
A1 = range(10)
A2 = [i for i in A1 if i in A0]
A3 = [A0[s] for s in A0]
A4 = [i for i in A1 if i in A3]
A5 = {i:i*i for i in A1}
A6 = [[i,i*i] for i in A1]
print(A0,'\n',A1,'\n',A2,'\n',A3,'\n',A4,'\n',A5,'\n',A6)

image
pythonpath变量是什么
pythonpath是python中一个重要的环境变量,用于在导入模块的时候搜索路径。因此它必须包含python源库目录以及含有python源代码的目录。剋手动设置pythonpath,但是通常python安装程序会把它呈现出来。
什么是切片
切片是python中的一种方法,切片可以只检索列表、元素或自渡川的一部分。在切片是需要使用切片操作符[].
image
print函数调用python中底层的什么方法
print函数默认调用sys.stdout.write方法,即往控制台打印字符串。
连接字符串用join还是+?
当用操作符+连接字符串的时候,每执行一次+都会申请一块新的内存,然后复制上一个+操作的结果和本次操作的右操作符到这块内存空间,因此用+连接字符串的时候会涉及好几次内存申请和复制。而join在连接字符串的时候,会先计算需要多大的内存存放结果,然后一次性申请所需内存并将字符串复制过去,这就是为什么join的性能优于+的原因。所以在连接字符串数组的时候,应考虑优先使用join。
元组的解封装是什么
image
将值解封装到变量x,y,z中
image

posted @ 2021-03-25 13:24  MTcx  阅读(301)  评论(0编辑  收藏  举报