面试题0010
2019-12-02 本文已影响0人
羋学僧
看代码写结果,内存中的列表
def extendList(val,li =[]):
li.append(val)
return li
list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')
print(list1)
print(list2)
print(list3)
[10, 'a']
[123]
[10, 'a']
参数变量在编译时会生成,而且只会生成一次,其内存地址的指向不发生变化,所以会有默认的
[]
1和3都会使用默认的编译生成的同一个
[]
2新生成一个
[]
一行代码生成九九乘法表
print('\n'.join([' '.join(['{}*{} = {}'.format(x,y,x*y) for y in range(1,x+1)]) for x in range(1,10)]))
分解
[x for x in range(1,10)]
[([x*y for y in range(1,x+1)]) for x in range(1,10)]
[(['{}*{} = {}'.format(x,y,x*y) for y in range(1,x+1)]) for x in range(1,10)]
[' '.join(['{}*{} = {}'.format(x,y,x*y) for y in range(1,x+1)]) for x in range(1,10)]
'\n'.join([' '.join(['{}*{} = {}'.format(x,y,x*y) for y in range(1,x+1)]) for x in range(1,10)])
合并两个列表,不能有重复元素
alist = ['a','b','c','d','e','f']
blist = ['x','y','z','d','e','f']
def merge_list(*args):
s = set()
for i in args:
s = s.union(i)
return list(s)
merge_list(alist,blist)
>>>['z', 'f', 'x', 'y', 'd', 'c', 'a', 'e', 'b']
def merge_list(*args):
q = []
for i in args:
q = q + i
return list(set(q))
merge_list(alist,blist)
>>>['z', 'd', 'c', 'x', 'e', 'y', 'b', 'f', 'a']
一行代码实现对列表a中的偶数位置(索引号)的元素进行加3后求和
testlist = [1,2,3,4,5,6,7,8]
result =sum(map(lambda x:testlist[x]+3,filter(lambda x:x%2==0,range(len(testlist)))))
print(result)
>>>28
sum(list(map(lambda x:x+3,testlist[0::2])))
sum([testlist[x] + 3 for x in range(len(testlist)) if x % 2 == 0])
sum([x+3 for x in testlist[0::2]])