Python笔试题(一)

1.列表(list)和元组(tuple)的区别

列表是可以修改的
元组不能修改

定义:
list: 链表, 有序的项目, 通过索引进行查找, 使用方括号"[]";
tuple:元组, 元组将多样的对象集合到一起, 不能修改, 通过索引进行查找, 使用括号"()";
dict:字典, 字典是一组键(key)和值(value)的组合, 通过键(key)进行查找, 没有顺序, 使用大括号"{}";
set:集合,无序, 元素只出现一次, 自动去重, 使用"set([])"; 应用场景:
1. list, 简单的数据集合, 可以使用索引;
2. tuple, 把一些数据当做一个整体去使用, 不能修改;
3. dict, 使用键值和值进行关联的数据;
4. set, 数据只出现一次, 只关心数据是否出现, 不关心其位置;

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

2. 集合(set)是怎样的一种数据类型,何时使用?


set集合,是一个无序且不重复的元素集合。
集合对象是一组无序排列的可哈希的值,集合成员可以做字典中的键。集合支持用innot in
操作符检查成员,由len()内建函数得到集合的基数(大小), 用 for 循环迭代集合的成员。但是
因为集合本身是无序的,不可以为集合创建索引或执行切片(slice)操作,也没有键(keys)可用
来获取集合中元素的值。

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

3.请在下面的空白处填写运行结果


>>>seq = [1, 2, 3, 4]
>>>seq[:2]
_____________________________
>>>seq[-2:]
_____________________________
>>>seq[10:]
_____________________________
>>>seq[::-1]
_____________________________
>>>seq[:]
_____________________________
>>> id(seq[:]) == id(seq)
_____________________________

>>> seq = [1, 2, 3, 4]
>>> seq[-2]
3
>>> seq[10:]
[]
>>> seq[10]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> seq[::-1]
[4, 3, 2, 1]
>>> seq[:]
[1, 2, 3, 4]
>>> id(seq[:]) == id(seq)
False
>>> 


  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

4.优化以下程序

result = []
for x in range(10):
result.append(x ** 2)
print(result)
优化后
>>> result = [x**2 for x in range(10)]
>>> print result
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> 

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

5.函数、类方法定义中如何实现可选参数、可选关键词参数

def funcArgsTest(a,b,c=100,*argc,**kwarg):
    sum = a + b + c
    for d in argc:
        sum += d
    for v in kwarg.itervalues():
        sum += v
    return sum

print funcArgsTest(100,200,300,500,600,aa=700,bb=900,cc=1000)

==>4300

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

6.请解释classmethod和staticmethod的区别

class ClassTest(object):
    def __init__(self,a):
        self.a = a
    def printk(self):
        print "a is ",self.a

    @classmethod
    def class_method(*args):
        print  "args is ",args


    @classmethod
    def class_method2(cls):
        print "cls is ",cls


    @staticmethod
    def static_method(*args):
        print "args is ",args

ct = ClassTest(100)
ct.printk()
ct.class_method()
ct.static_method()
ct.class_method2()

==>
a is  100
args is  (<class '__main__.ClassTest'>,)
args is  ()
cls is  <class '__main__.ClassTest'>

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

7. 请给出下列程序的运行结果

>>>x = 0.5
>>>while x != 1.0
>>>print(x)
>>> x += 0.1
此题考查浮点数比较相等的情况,x != 1.0 这样程序并不会结束
因为浮点数相等比较不能通过==,应该是一个范围,可以使用 x <= 1.0

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

8.请写一段程序,包含迭代器和生成器的使用

>>> for xa in (x for x in range(10)):
...    print xa
... 
0
1
2
3
4
5
6
7
8
9


  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

9.请根据age分别对student_tuples及student_objects进行排序

>>>student_tuples = [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'B', 10),
]
说明:每一行的三个元素分别代表name, grade, age.
>>> class Student:
def __init__(self, name, grade, age):
self.name = name
self.grade = grade
self.age = age
def __repr__(self):
return repr((self.name, self.grade, self.age))
>>>student_objects = [
Student('john', 'A', 15),
Student('jane', 'B', 12),
Student('dave', 'B', 10),


sorted(student_tuples,key = lambda x : x[2])
sorted(student_objects,key = lambda s : s.age)


class Student:

   def __init__(self, name, grade, age):

      self.name = name

      self.grade = grade

      self.age = age

   def __repr__(self):
      return repr((self.name, self.grade, self.age))

student_objects = [

Student('john', 'A', 15),

Student('jane', 'B', 12),

Student('dave', 'B', 10),
]
print sorted(student_objects,key = lambda s:s.age)


[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50

10.如何使用匿名函数


>>> map(lambda x : x**2,[1,2,3])
[1, 4, 9]
>>> filter(lambda x: x >1 ,[1,2,3])
[2, 3]
>>> map(lambda x : x**2,[1,2,3])
[1, 4, 9]
>>> reduce(lambda x,y: x + y,[1,2,3])
6
>>> filter(lambda x: x >1 ,[1,2,3])
[2, 3]
>>> 


  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

11.何时使用标准库 collections 中的deque?

deque其实是 double-ended queue 的缩写,翻译过来就是双端队列,它最大的好处就是实现了从队列 头部快速增加和取出对象: 
.popleft(), 
.appendleft()
但是值得注意的是,list对象的这两种用法的时间复杂度是 O(n) ,也就是说随着元素数量的增加耗时呈 线性上升。而使用deque对象则是 O(1) 的复杂度,所以当你的代码有这样的需求的时候, 一定要记得使用deque。

deque还可以限制队列长度,如果长于队列则会删除

如果是是append则会删除最左端的元素
如果是apppendleft则会删除最右端的元素

>>> dq = deque([],3)
>>> dq.append(1)
>>> dq.append(2)
>>> dq.append(3)
>>> print dq
deque([1, 2, 3], maxlen=3)
>>> dq.append(4)
>>> print dq
deque([2, 3, 4], maxlen=3)

>>> dq = deque([],3)
>>> print dq
deque([], maxlen=3)
>>> dq.append(1)
>>> dq.append(2)
>>> dq.append(3)
>>> print dq
deque([1, 2, 3], maxlen=3)
>>> dq.appendleft(4)
>>> print dq
deque([4, 1, 2], maxlen=3)
>>> 


collections中有几个非常好用的数据类型
Python拥有一些内置的数据类型,比如str, int, list, tuple, dict等, collections模块在这些内置数据类型的基础上,提供了几个额外的数据类型:

    namedtuple(): 生成可以使用名字来访问元素内容的tuple子类
    deque: 双端队列,可以快速的从另外一侧追加和推出对象
    Counter: 计数器,主要用来计数
    OrderedDict: 有序字典
    defaultdict: 带有默认值的字典

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43

12.标准库 copy 中的 copy 和deepcopy的区别

copy.copy()是浅拷贝
copy.deepcopy()是深拷贝
>>> import copy
>>> lista = [1,2,3,['a','b']]
>>> listb = copy.copy(lista)
>>> listc = copy.deepcopy(lista)
>>> lista
[1, 2, 3, ['a', 'b']]
>>> listb
[1, 2, 3, ['a', 'b']]
>>> listc
[1, 2, 3, ['a', 'b']]
>>> lista.append(5)
>>> lista
[1, 2, 3, ['a', 'b'], 5]
>>> listb
[1, 2, 3, ['a', 'b']]
>>> listc
[1, 2, 3, ['a', 'b']]
>>> id(lista)
3085189868L
>>> id(listb)
3084763820L
>>> id(listc)
3085198380L

>>> lista[3].append('c') 
>>> lista
[1, 2, 3, ['a', 'b', 'c'], 5]
>>> listb
[1, 2, 3, ['a', 'b', 'c']]
>>> listc
[1, 2, 3, ['a', 'b']]
>>> 

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

13.标准库 re 正则表达式 match 和 search 区别


re.match是从字符串首字母处匹配
re.search是遍历整个字符串匹配


>>> str1 = "<abc>aaa</abc>"
>>> re.match("<",str1)
<_sre.SRE_Match object at 0xb7dd7e90>
>>> m = re.match("<",str1)
>>> m.group()
'<'
>>> str1 = "xyz<abc>aaa</abc>"
>>> m = re.match("<",str1)
>>> m.group()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
>>> re.search("<",str1)
<_sre.SRE_Match object at 0xb7dd2988>
>>> ms = re.search("<",str1)
>>> ms.group()
'<'
>>> 


>>> import re
>>> help(re.match)
Help on function match in module re:

match(pattern, string, flags=0)
    Try to apply the pattern at the start of the string, returning
    a match object, or None if no match was found.

>>> help(re.search)
Help on function search in module re:

search(pattern, string, flags=0)
    Scan through string looking for a match to the pattern, returning
    a match object, or None if no match was found.


  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

14.使用正则表达式在’’’待处理

OPTION’’’字符串中, 获取OPTION的value属性值.注意: OPTION中可能有其他的标签属性,如: 或者


>>> str1 = '<OPTION value="TBD">TBD</OPTION>OPTION'

>>> m = re.match(r"(<OPTION\s+[a-z]*[=]*\w*\s*)(value=)(\"\w+\")",str1)
>>> m.group(3)
'"TBD"'


>>> str1 = '<OPTION  aa=2 value="TBD">TBD</OPTION>OPTION'
>>> m = re.match(r"(<OPTION\s+[a-z]*[=]*\w*\s*)(value=)(\"\w+\")",str1)
>>> m.group(3)
'"TBD"'



>>> str1 = '<OPTION  aa=2 value="TBD" bb=2>TBD</OPTION>OPTION'
>
>>> m = re.match(r"(<OPTION\s+[a-z]*[=]*\w*\s*)(value=)(\"\w+\")",str1)
>>> m.group(3)
'"TBD"'

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

15.如何使用标准库pdb调试 Python 程序

在python中使用pdb模块可以进行调试
import pdb
pdb.set_trace()

也可以使用python -m pdb myscript.py这样的方式
  
  
  • 1
  • 2
  • 3
  • 4
  • 5

16.什么是装饰器,如何使用装饰器

def log(level):
    def dec(func):
        def wrapper(*kargc,**kwargs):
            print "before func was called"
            func(*kargc,**kwargs)
            print "after func was called"
        return wrapper
    return dec

@log(2)
def funcLog():
    print "funcLog was called"

funcLog()

==>
before func was called
funcLog was called
after func was called

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

17.请解释with关键字的用法

with关键字的前提是类需要实现__enter__和__exit__
>>> with open("test.sh") as f:
...    f.read()

  
  
  • 1
  • 2
  • 3
  • 4

18.参数传递使用的是传递引用还是传递值?为什么?

对于变量(与对象相对的概念),其实,python函数参数传递可以理解为就是变量传值操作

不可变对象参数调用

def ChangeInt( a ):
    a = 10
nfoo = 2 
ChangeInt(nfoo)
print nfoo #结果是2


可变对象参数调用

def ChangeList( a ):
    a[0] = 10
lstFoo = [2]
ChangeList(lstFoo )
print nfoo #结果是[10]


  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

19.在类的方法定义中’self’是怎样的一个参数


selfPython里不是关键字。self代表当前对象的地址。self能避免非限定调用造成的全局变量。
self在定义时需要定义,但是在调用时会自动传入。
self的名字并不是规定死的,但是最好还是按照约定是用self
self总是指调用时的类的实例

  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

20.说明CPython的内存管理机制


变量的存储有三个区域,事先分配的静态内存、事先分配的可重复利用内存以及需要通过mallocfree来控制的自由内存。
python的内存在底层也是由mallocfree的方式来分配和释放,只是它代替程序员决定什么时候分配什么时候释放,同时也提供接口让用户手动释放,因此它有自己的一套内存管理体系,主要通过两种机制来实现,一个是引用计数,一个是垃圾回收。前者负责确定当前变量是否需要释放,后者解决前者解决不了的循环引用问题以及提供手动释放的接口del。

  
  
  • 1
  • 2
  • 3
  • 4

转载自:http://blog.csdn.net/u013679490/article/details/54948759

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值