Python基础面试题


1、Python中字符串格式化, %s和.format 的主要区别是啥?
不需要指定类型
Python中用Tuple将多个值传递给模板,每个值对应一个字符,而str.format(),通过{}来代替传统的%

2、

list = ['a', 'b', 'c', 'd', 'e']
print(list[10:])
# 输出为[]

Python的切片语法不会出现索引越界的问题
官方文档解释:

The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j.
If i or j is greater than len(s), use len(s). If i is omitted or None, use 0.
If j is omitted or None, use len(s).
If i is greater than or equal to j, the slice is empty.

也就是说:

  • 当左或右索引值大于序列的长度值时,就用长度值作为该索引值;
  • 当左索引值缺省或者为 None 时,就用 0 作为左索引值;
  • 当右索引值缺省或者为 None 时,就用序列长度值作为右索引值;
  • 当左索引值大于等于右索引值时,切片结果为空对象。
    参考博客
    https://cloud.tencent.com/developer/article/1922063

3、

list = [ [ ] ] * 5
print(list)
# 输出为 [[], [], [], [], []]

print(list)
# 输出为 [[10], [10], [10], [10], [10]]
list[1].append(20)
print(list)
# 输出为 [[10, 20], [10, 20], [10, 20], [10, 20], [10, 20]]
list.append(30)
print(list)
# 输出为 [[10, 20], [10, 20], [10, 20], [10, 20], [10, 20], 30]

[[]] * 5就是简单的创造了5个空列表,是创建了包含对同一个列表五次引用的列表,list[0].append(10) 是将10附加在第一个列表上,

4、
使用单一的列表生成式来产生一个新的列表,该列表只包含满足以下条件的值:

(a)偶数值

(b)元素为原始列表中偶数切片。

t = [x for x in list[::2] if x%2 == 0]

5、 dict 和json的区别
字典是一种数据结构,而json(JavaScript Object Notation)是一种数据格式,纯字符串,二者通过python内置的JOSN 库来进行转换
通过对JSON序列化,用Python的json库中的dump()方法可以将Json转成Python对象
load 方法
对比:
1.json的key只能是字符串,python的dict可以是任何可hash对象(hashtable type);
  2、json的key可以是有序、重复的;dict的key不可以重复。
  3、json的value只能是字符串、浮点数、布尔值或者null,或者它们构成的数组或者对象。
  4、json任意key存在默认值undefined,dict默认没有默认值;
  5、json访问方式可以是[],也可以是.,遍历方式分in、of;dict的value仅可以下标访问。
  6、json的字符串强制双引号,dict字符串可以单引号、双引号;
  7、dict可以嵌套tuple,json里只有数组。
  8、json:true、false、null
  9、python:True、False、None
  10、json中文必须是unicode编码,如"\u6211".
  11、json的类型是字符串,字典的类型是字典。
python中的基本类型都是Hashtable,如str、bytes、数字类型、tuple等;

json.load() : it accepts a file object. To read JSON data from a file and convert it into a dictionary.
Json.loads(): to convert JSON string to a dictionary. Sometimes we receive JSON response in string format.
So to use it in our application, we need to convert JSON string into a Python dictionary.
Json.dump(): Used for writing the Python object i.e. dict to JSON file.
Json.dumps(): method can convert a Python object into a JSON string.

将json file 用json.load来加载request,然后用json.dumps()转换成json string来发送请求
最后用json.loads将接口返回的json string 转化成dict
json file -> json string-> dict

6、

def extendList(val, list=[]):
    list.append(val)
    return list

list1 = extendList(10) # print [10, 'a']
list2 = extendList(123,[]) # print [123]
list3 = extendList('a') # print [10, 'a']

带有默认参数的表达式在函数定义的时候被计算的,不是在函数调用时候被计算,因此list1和list3是默认在一个列表上操作的,而list2是在一个分离的列表上进行操作的,
操作之前先判断list是否为空,可以达到目的

def extendList(val, list=None):
    if list is None:
        list = []
    list.append(val)
    return list
   

参考博客:
https://www.php.cn/python-tutorials-415526.html