集锦 | 53个Python面试问题 答案打包带走
列表是可变的。创建后可以对其进行修改。 元组是不可变的。元组一旦创建,就不能对其进行更改。 列表表示的是顺序。它们是有序序列,通常是同一类型的对象。比如说按创建日期排序的所有用户名,如['Seth', 'Ema', 'Eli']。 元组表示的是结构。可以用来存储不同数据类型的元素。比如内存中的数据库记录,如(2, 'Ema', '2020–04–16')(#id, 名称,创建日期)。
name = 'Chris'# 1. f stringsprint(f'Hello {name}')# 2. % operatorprint('Hey %s %s' % (name, name))# 3. formatprint( 'My name is {}'.format((name)))
a = [1,2,3]b = ac = [1,2,3]
print(a == b)
print(a == c)
#=> True
#=> True
print(a is b)print(a is c)#=> True#=> False
print(id(a))
print(id(b))
print(id(c))
#=> 4369567560
#=> 4369567560
#=> 4369567624
def logging(func): def log_function_called(): print(f'{func} called.') func() return log_function_called
def my_name():
print('chris')def friends_name():
print('naruto')my_name()
friends_name()
#=> chris
#=> naruto
@loggingdef my_name(): print('chris')@loggingdef friends_name(): print('naruto')my_name()friends_name()#=> <function my_name at 0x10fca5a60> called.#=> chris#=> <function friends_name at 0x10fca5f28> called.#=> naruto
[i for i in range(10)]
#=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[i for i in range(2,10)]#=> [2, 3, 4, 5, 6, 7, 8, 9]
[i for i in range(2,10,2)]
#=> [2, 4, 6, 8]
class Car : def __init__(self, color, speed): self.color = color self.speed = speedcar = Car('red','100mph')car.speed#=> '100mph'
class CoffeeShop:
specialty = 'espresso'
def __init__(self, coffee_price):
self.coffee_price = coffee_price
# instance method
def make_coffee(self):
print(f'Making {self.specialty} for ${self.coffee_price}')
# static method
@staticmethod
def check_weather():
print('Its sunny') # class method
@classmethod
def change_specialty(cls, specialty):
cls.specialty = specialty
print(f'Specialty changed to {specialty}')
coffee_shop = CoffeeShop('5')coffee_shop.make_coffee()#=> Making espresso for $5
coffee_shop.check_weather()
#=> Its sunny
coffee_shop.change_specialty('drip coffee')#=> Specialty changed to drip coffeecoffee_shop.make_coffee()#=> Making drip coffee for $5
def func():
print('Im a function')
func
#=> function __main__.func>func()
#=> Im a function
def add_three(x): return x + 3li = [1,2,3][i for i in map(add_three, li)]#=> [4, 5, 6]
from functools import reduce
def add_three(x,y):
return x + y
li = [1,2,3,5]
reduce(add_three, li)
#=> 11
def add_three(x): if x % 2 == 0: return True else: return Falseli = [1,2,3,4,5,6,7,8][i for i in filter(add_three, li)]#=> [2, 4, 6, 8]
name = 'chr'
def add_chars(s):
s += 'is'
print(s)
add_chars(name)
print(name)
#=> chris
#=> chr
li = [1,2]def add_element(seq): seq.append(3) print(seq)add_element(li) print(li)#=> [1, 2, 3]#=> [1, 2, 3]
li = ['a','b','c']
print(li)
li.reverse()
print(li)
#=> ['a', 'b', 'c']
#=> ['c', 'b', 'a']
'cat' * 3#=> 'catcatcat'
[1,2,3] * 2
#=> [1, 2, 3, 1, 2, 3]
class Shirt:
def __init__(self, color):
self.color = color
s = Shirt('yellow')
s.color
#=> 'yellow'
a = [1,2]
b = [3,4,5]
a + b
#=> [1, 2, 3, 4, 5]
li1 = [['a'],['b'],['c']]li2 = li1li1.append(['d'])print(li2)#=> [['a'], ['b'], ['c'], ['d']]
li3 = [['a'],['b'],['c']]
li4 = list(li3)
li3.append([4])
print(li4)
#=> [['a'], ['b'], ['c']]
li3[0][0] = ['X']
print(li4)
#=> [[['X']], ['b'], ['c']]
import copyli5 = [['a'],['b'],['c']]li6 = copy.deepcopy(li5)li5.append([4])li5[0][0] = ['X']print(li6)#=> [['a'], ['b'], ['c']]
列表存在于python的标准库中。数组由Numpy定义。 列表可以在每个索引处填充不同类型的数据。数组需要同构元素。 列表上的算术运算可从列表中添加或删除元素。数组上的算术运算按照线性代数方式工作。 列表还使用更少的内存,并显著具有更多的功能。
import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
np.concatenate((a,b))
#=> array([1, 2, 3, 4, 5, 6])
a = 5.12345round(a,3)#=> 5.123
a = [0,1,2,3,4,5,6,7,8,9]
print(a[:2])
#=> [0, 1]
print(a[8:])
#=> [8, 9]
print(a[2:8])
#=> [2, 3, 4, 5, 6, 7]
print(a[2:8:2])
#=> [2, 4, 6]
import pickleobj = [ {'id':1, 'name':'Stuffy'}, {'id':2, 'name': 'Fluffy'}]with open('file.p', 'wb') as f: pickle.dump(obj, f)with open('file.p', 'rb') as f: loaded_obj = pickle.load(f)print(loaded_obj)#=> [{'id': 1, 'name': 'Stuffy'}, {'id': 2, 'name': 'Fluffy'}]
a = [False, False, False]
b = [True, False, False]
c = [True, True, True]
print( any(a) )
print( any(b) )
print( any(c) )
#=> False
#=> True
#=> True
print( all(a) )
print( all(b) )
print( all(c) )
#=> False
#=> False
#=> True
import sklearn
from sklearn import cross_validation
value = 5value += 1print(value)#=> 6value -= 1value -= 1print(value)#=> 4
bin(5)
#=> '0b101'
a = [1,1,1,2,3]a = list(set(a))print(a)#=> [1, 2, 3]
'a' in ['a','b','c']
#=> True
'a' in [1,2,3]
#=> False
a = [1,2,3]b = [1,2,3]a.append(6)print(a)#=> [1, 2, 3, 6]b.extend([4,5])print(b)#=> [1, 2, 3, 4, 5]
abs(2
#=> 2
abs(-2)
#=> 2
a = ['a','b','c']
b = [1,2,3]
[(k,v) for k,v in zip(a,b)]
#=> [('a', 1), ('b', 2), ('c', 3)]
d = {'c':3, 'd':4, 'b':2, 'a':1}
sorted(d.items())
#=> [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
class Car(): def drive(self): print('vroom')class Audi(Car): passaudi = Audi()audi.drive()
s = 'A string with white space'
''.join(s.split())
#=> 'Astringwithwhitespace'
li = ['a','b','c','d','e']for idx,val in enumerate(li): print(idx, val)#=> 0 a#=> 1 b#=> 2 c#=> 3 d#=> 4 e
a = [1,2,3,4,5]
for i in a:
if i > 3:
pass
print(i)
#=> 1
#=> 2
#=> 3
#=> 4
#=> 5
for i in a: if i < 3: continue print(i)#=> 3#=> 4#=> 5
for i in a:
if i == 3:
break
print(i)
#=> 1
#=> 2
a = [1,2,3,4,5]
a2 = []
for i in a:
a2.append(i + 1)print(a2)
#=> [2, 3, 4, 5, 6]
a3 = [i+1 for i in a]
print(a3)
#=> [2, 3, 4, 5, 6]
x = 5y = 10'greater' if x > 6 else 'less'#=> 'less''greater' if y > 6 else 'less'#=> 'greater'
'123abc...'.isalnum()
#=> False'
123abc'.isalnum()
#=> True
'123a'.isalpha()#=> False'a'.isalpha()#=> True
d = {'id':7, 'name':'Shiba', 'color':'brown', 'speed':'very slow'}list(d)#=> ['id', 'name', 'color', 'speed']
small_word = 'potatocake'big_word = 'FISHCAKE'small_word.upper()#=> 'POTATOCAKE'big_word.lower()#=> 'fishcake'
li = ['a','b','c','d']
li.remove('b')
li
#=> ['a', 'c', 'd']
li = ['a','b','c','d']
del li[0]
li
#=> ['b', 'c', 'd']
li = ['a','b','c','d']
li.pop(2)
#=> 'c'
li
#=> ['a', 'b', 'd']
52. 举一个递推式构造字典(dictionary comprehension)的例子
# creating a list of lettersimport stringlist(string.ascii_lowercase)alphabet = list(string.ascii_lowercase)# list comprehensiond = {val:idx for idx,val in enumerate(alphabet)}d#=> {'a': 0,#=> 'b': 1,#=> 'c': 2,#=> ...#=> 'x': 23,#=> 'y': 24,#=> 'z': 25}
try:
# try to do this
except:
# if try block fails then do this
finally:
# always do this
try:
val = 1 + 'A'
except:
val = 10
finally:
print('complete')
print(val)
#=> complete
#=> 10
赞 (0)