[Python习题] 常见题系列一

参考文章:
https://blog.csdn.net/weixin_40862231/article/details/79504455

1. python中is和==的区别

Python中的对象包含三要素:id、type、value。
其中id用来唯一标识一个对象,type标识对象的类型,value是对象的值。
is判断的是a对象是否就是b对象,是通过id来判断的。
==判断的是a对象的值是否和b对象的值相等,是通过value来判断的。

>>>d = {'a':1,'b':2}
>>>dd =d.copy()
>>>dd
{'a': 1, 'b': 2}
>>>dd is d
False
>>>dd == d
True

2. read、readline、readlines的区别

.read() 每次读取整个文件,它通常将读取到的文件内容放到一个字符串变量中,也就是说 .read() 生成文件内容是一个字符串类型.

>>>fopen = open('D:\\test.txt','r')  #r以只读方式打开,默认方式
>>>x = fopen.read()
>>>print(x)
hello
123
hello world
>>>type(x)
<type 'str'>

.readline()每次读取文件的一行,通常也是读取到的一行内容放到一个字符串变量中,返回str类型

>>>fopen = open('D:\\test.txt','r')
>>>x = fopen.readline()
>>>print(x)
hello
>>>print(type(x))
<type 'str'>

.readlines()每次按行读取整个文件内容,将读取到的内容放到一个列表中,返回list类型

>>>fopen = open('d:\\test.txt','r')
>>>x = fopen.readlines()
>>>print(x)
['hello\n', '123\n', 'hello world']
>>>type(x)
<type 'list'>

3. 创建字典的方法

#使用字典 方法1
>>>dict1 = {'a':1,'b':2}
>>>print(dict1['b'])
2

#使用字典 方法2
>>>dict2 = {}
>>>dict2['key1'] = 12
>>>dict2['key2'] = 23
>>>print(dict2)
{'key2': 23, 'key1': 12}
>>>print(dict2['key2'])
23

#使用dict()函数 方法3
>>>dict3 = dict(key1=12, key2='world')     #key不加引号                       
>>>print(dict3)
{'key2': 'world', 'key1': 12}
>>>print(dict3['key1'])      #key加引号
12

#使用dict()函数 方法4
>>>a0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))
>>>a0
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}

4. *args,**kwargs的使用

当函数的参数不确定时,可以使用*args 和**kwargs,*args 没有key值,**kwargs有key值。

# 1. *args可以当作可容纳多个变量组成的list
def fun_var_args(farg, *args):  
    print "arg:", farg  
    for value in args:  
        print "another arg:", value  

fun_var_args(1, "two", 3)   

#输出
arg: 1  
another arg: two  
another arg: 3  

# 2. **kwargs可以当作容纳多个key和value的dictionary  
def fun_var_kwargs(farg, **kwargs):  
    print "arg:", farg  
    for key in kwargs:  
        print "another keyword arg: %s: %s" % (key, kwargs[key])  

fun_var_kwargs(farg=1, myarg2="two", myarg3=3) 

#输出
arg: 1  
another keyword arg: myarg2: two  
another keyword arg: myarg3: 3  

5. python中match()和search()的区别

re 模块使 Python 语言拥有全部的正则表达式功能。
re.match与re.search的区别
re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None
re.search匹配整个字符串,直到找到一个匹配。

import re
a ='www.baidu.com'
b ='www'
c ='com'
print(re.match(b,a))
print(re.match(b,a).span())
print(re.match(c,a))
print(re.search(b,a).span())
print(re.search(c,a).span())

#输出
<_sre.SRE_Match object at 0x00000000027234A8>
(0, 3)
None
(0, 3)
(10, 13)

6. 返回某文件夹中所有文件的全路径

import os
def print_directory(spath):
    files_list = os.listdir(spath)
    for file in files_list:
        print(os.path.realpath(file))

print_directory('D:\\BaiduNetdiskDownload')

7. 写出代码中变量的最终值

>>>a0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))
>>>a0
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}

>>>a1 = range(10)
>>>a1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  #生成列表

>>>a2 = [i for i in a1 if i in a0]
>>>a2
[]

>>>a3 = [a0[s] for s in a0] # dictionary循环时默认为key
>>>a3
[1, 3, 2, 5, 4]

>>>a4 = [i for i in a1 if i in a3]
>>>a4
[1, 2, 3, 4, 5]

8. 实现Python中list去重

set()函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。

#方法1
>>>list1 = [1,1,2,2,3,4]
>>>list1 = set(list1)
>>>list1
set([1, 2, 3, 4])
>>>list2 = list(list1)
>>>list2
[1, 2, 3, 4]

#方法2
>>>list1 = [1,1,2,2,3,4]
>>>list2 = []
>>>for i in list1:
>>>    if i not in list2:
>>>        list2.append(i)

>>>list2
[1, 2, 3, 4]

9. yield的作用与使用

保存当前运行状态(断点),然后暂停执行,即将函数挂起
将yeild关键字后面表达式的值作为返回值返回,此时可以理解为起到了return的作用,当使用next()、send()函数让函数从断点处继续执行,即唤醒函数。

要创建一个generator,有很多种方法。第一种方法很简单,只要把一个列表生成式的[]改成(),就创建了一个generator:

>>> L = [x * x for x in range(10)]
>>> L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> g = (x * x for x in range(10))
>>> g
 at 0x1022ef630>

创建L和g的区别仅在于最外层的[]和(),L是一个list,而g是一个generator。

如果一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数,而是一个generator:
generator和函数的执行流程不一样。函数是顺序执行,遇到return语句或者最后一行函数语句就返回。而变成generator的函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。
举个简单的例子,定义一个generator,依次返回数字1,3,5:

def odd():
    print('step 1')
    yield 1
    print('step 2')
    yield(3)
    print('step 3')
    yield(5)

调用该generator时,首先要生成一个generator对象,然后用next()函数不断获得下一个返回值:

>>> o = odd()
>>> next(o)
step 1
1
>>> next(o)
step 2
3
>>> next(o)
step 3
5
>>> next(o)
Traceback (most recent call last):
  File "", line 1, in <module>
StopIteration

可以看到,odd不是普通函数,而是generator,在执行过程中,遇到yield就中断,下次又继续执行。执行3次yield后,已经没有yield可以执行了,所以,第4次调用next(o)就报错。
基本上从来不会用next()来获取下一个返回值,而是直接使用for循环来迭代

for n in odd():
    print(n)

实例:输出斐波那契數列前 N 个数

def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b
        n = n + 1
    return 'done'
>>> for n in fib(6):
...     print(n)
...
1
1
2
3
5
8

10. lambda函数介绍

lambda函数是匿名函数;
使用lambda函数能够创建小型匿名函数;
该函数省略了用def声明函数的标准步骤。
实例

>>>f = lambda x,y:x+y # 求两个函数的和。 x,y是参数,x+y是函数返回值
>>>f(2,3)
5

你可能感兴趣的:(Python)