Python面试100讲-Chapter 2-优快云

Python面试100讲-优快云

Chapter 2:列表、元组与字典

1. 对列表元素进行去重

1. 在Python中如何定义集合,集合与列表有什么区别

a=[1,2,3,4,5]
print(type(a))  # list

b = (1,2,3,4,5)
print(type(b)) # tuple

c = {1,2,3,4,5}
print(type(c)) # set

区别:

  1. 集合没有重复的元素,列表可以有重复的元素
  2. 集合中的元素与顺序无关,列表中的元素与顺序有关
a=[1,2,3,4,5,4,5]
c={1,2,3,4,5,4,5}
print(a) # [1,2,3,4,5,4,5]
print(c) # {1,2,3,4,5}

a1 = [1,2,3]
a2 = [3,2,1]
print(a1==a2) # False

b1 = {1,2,3}
b2 = {3,2,1}
print(b1 == b2} # True

2. 如何去掉列表(元组 )中的重复元素

a=[1,2,3,4,5,4,5]
print(list(set(a))) # [1,2,3,4,5]

2. 集合的并与交

1. 如何向集合中添加和删除元素,需要注意什么

x = {3,2,1}
x.add(123)
print(x) # {123,1,2,3}
x.add(1)
print(x) # {123,1,2,3}
x.add('abc')
print(x) # {123,1,2,3,'abc'}
# 删除
x.remove(123)
if x.__contains__(444):
	x.remove(444)
else:
	print('444在集合中不存在')

2. 如何求集合的并、交,集合之间是否还支持其他操作

x = {3,2,1}
y = {3,4,5}
print(x | y) # {1,2,3,4,5} 集合之间的合并
print(x.union(y)) # {1,2,3,4,5} 集合之间的合并

print(x & y) # {3} 集合之间的相交
print(x.intersection(y)) # {3} 集合之间的相交

print(x.difference(y)) # {1,2} x中存在,而在y中不存在的元素。集合的减法

print(x ^ y) # {1,2,4,5} 并集中减去交集

3. 如何让两个列表首尾相接

1. 连接两个列表的方式有哪些

a=[1,5,7,9,6]
b=[2,3,3,6,8]

print(a+b) # [1, 5, 7, 9, 6, 2, 3, 3, 6, 8]
a.extend(b) 
print(a)# [1, 5, 7, 9, 6, 2, 3, 3, 6, 8]

2. 这些连接方式有什么区别?

'''
1. +号不改变参与连接的列表的值,但extend方法会改变调用方法的列表的值
2. +号两侧要么都是元组,要么都是列表。列表的extend方法可以将元组添加到列表后面
'''
a=[1,5,7,9,6]
c=(1,2,3)
a.extend(c)
print(a) # [1,5,7,9,6,1,2,3]
print(a+c) # Error

元组本身是只读的,所以元组没有extend方法

4. 打乱列表元素顺序的方式

1. 编写一个函数(不要使用Python模块的函数),打乱列表元素的顺序

a=[1,2,3,4,5,6,7,8,9,0]
import random

def random_list1(a):
	for i in range(0,100):
		index1 = random.randint(0,len(a)-1)
		index2 = random.randint(0,len(a)-1)
		a[index1], a[index2] = a[index2], a[index1]
	return a

b = random_list1(a)
print(b)

a=[1,2,3,4,5,6,7,8,9,0]
def random_list2(a):
	a_copy = a.copy()
	result = []
	count = len(a)
	for i in range(0, count):
		index = random.randint(0,len(a_copy)-1)
		result.append(a_copy[index])
		a_copy.pop(index)
	return result

b = random_list2(a)
print(b)

2. 如何对列表元素进行随机排列

import random
a=[1,2,3,4,5,6,7,8,9,0]
random.shuffle(a)
print(a)

5. 单星(*)和双星(**)运算符

1. 单星(*)和双星(**)运算符的作用,请举例说明

# 单星(*)
# 以元组形式导入可变参数

def fun1(param1, *param2):
	print('param1:',param1)
	print('param2:',param2, type(param2))

fun1(1,2,3,4,5)
'''
param1: 1
param2: (2, 3, 4, 5) <class 'tuple'>
'''
# 双星(**)
# 以字典形式导入

def fun2(param1, **param2):
	print('param1:',param1)
	print('param2:',param2, type(param2))

fun2(1,x=2,y=3,z=4)
'''
param1: 1
param2: {'x': 2, 'y': 3, 'z': 4} <class 'dict'>
'''

2. 请描述合并列表和字典的方法有哪些

a=[1,2,3]
b=[4,5,6]

x=[*a,*b]
print(x) # [1,2,3,4,5,6]

m={'x': 2, 'y': 3, 'z': 4}
n={'a': 2, 'b': 3, 'c': 4}
l={**m,**n}
print(l) # {'x': 2, 'y': 3, 'z': 4, 'a': 2, 'b': 3, 'c': 4}

6. 快速调换字典中的key和value(生成式)

1. 如何快速调换字典中的key和value

d={'a':1,'b':2}
print({v:k for k,v in d.items()}) # {1: 'a', 2: 'b'}

2. 如何用循环快速生成一个从0到100的列表

a = [i for i in range(101)]

7. 将两个列表或元组合并成一个字典

1. 如何将两个列表或元组合并成一个字典,形式如下:

a=['a','b']
b=[1,2]

合并后:{'a':1,'b':2}

a=['a','b']
b=[1,2]
print(dict(zip(a,b))) # {'a':1,'b':2}

print(zip.__doc__)
'''
zip(iter1 [,iter2 [...]]) --> zip object

Return a zip object whose .__next__() method returns a tuple where
the i-th element comes from the i-th iterable argument.  The .__next__()
method continues until the shortest iterable in the argument sequence
is exhausted and then it raises StopIteration.
'''

fields=('id','name','age')
records=[['01','Bill',20],['02','Mike',30]]
result=[]
for record in records:
	result.append(dict(zip(fields,record)))

print(result) # [{'id': '01', 'name': 'Bill', 'age': 20}, {'id': '02', 'name': 'Mike', 'age': 30}]

8. 详细描述列表与元组的差异

1. 详细描述列表与元组的差异,并举例说明

# 四个区别

#1:语法差异
a=(1,2,3,4)
b=[1,2,3,4]

#2. 元组是只读的,列表是可读写的
a[1]=3 # Error
b[1]=3 # No Error

#3.
copy_a = tuple(a)
print(a is copy_a) # True

copy_b = list(b)
print(b is copy_b) # False

#4. 大小不同,元组占用的空间更小
print(a.__sizeof__()) # 56
print(b.__sizeof__()) # 72

9. 如何排序一个列表

1. 对列表排序有哪几种方法

a=[1,5,7,9,6,1,2,3]
a.sort()
print(a) # [1, 1, 2, 3, 5, 6, 7, 9]

b=[1,5,7,9,6,1,2,3]
c=sorted(b)
print(c) # [1, 1, 2, 3, 5, 6, 7, 9]

2. 列表的sort方法与sorted函数都可以对列表进行排序,它们有什么区别?

'''
1. sort属于列表,sorted是独立的函数
2. sort改变列表本身,sorted返回一个新的排好序的列表
'''

3. 如何倒序排列一个列表

a=[1,5,7,9,6,1,2,3]
a.sort(reverse=True)
print(a) # [9, 7, 6, 5, 3, 2, 1, 1]

a=[1,5,7,9,6,1,2,3]
c = sorted(a,reverse=True)
print(c) # [9, 7, 6, 5, 3, 2, 1, 1]

10. 如果列表元素是对象,该如何排序

1. 如果列表元素是对象,对这样的列表排序有哪些方法?

class MyClass(object):
	def __init__(self):
		self.value = 0
	def __lt__(self, other):
		return self.value < other.value
	def __gt__(self,other):
		return self.value > other.value

my1 = MyClass()
my1.value = 20

my2 = MyClass()
my2.value  = 10

my3 = MyClass()
my3.value = 30

a=[my1,my2,my3]
a.sort()
for i in a:
	print(i.value)

'''
10
20
30
'''
class MyClass(object):
	def __init__(self):
		self.value = 0
my1 = MyClass()
my1.value = 20

my2 = MyClass()
my2.value  = 10

my3 = MyClass()
my3.value = 30

a=[my1,my2,my3]

import operator

a.sort(key=operator.attrgetter('value'))

for i in a:
	print(i.value)

'''
10
20
30
'''

2. 如果列表元素是对象,进行倒序排序有哪些方法?

class MyClass(object):
	def __init__(self):
		self.value = 0


my1 = MyClass()
my1.value = 20

my2 = MyClass()
my2.value  = 10

my3 = MyClass()
my3.value = 30

a=[my1,my2,my3]

import operator

a.sort(key=operator.attrgetter('value'), reverse=True)

for i in a:
	print(i.value)
# 修改__lt__ 和 __gt__的返回值

11. del和pop在删除列表元素上有什么区别

1. del和pop都可以用来删除列表元素,那么它们有什么区别

a=[4,123,5,6,3,9]

print(a) # [4, 123, 5, 6, 3, 9]
del a[2]
print(a) # [4, 123, 6, 3, 9]

print(a.pop(1)) # 123
print(a) # [4, 6, 3, 9]

print(a.pop()) # 9

12. 用lambda表达式对列表进行排序

1. 如果列表元素是字典类型,如何利用lambda表达式对列表进行升降序排列

a=[
	{'name':'Bill','age':40},
	{'name':'Mike','age':12},
	{'name':'John','age':29}
]

print(a) # [{'age': 40, 'name': 'Bill'}, {'age': 12, 'name': 'Mike'}, {'age': 29, 'name': 'John'}]
print(sorted(a,key=lambda x:x['age'])) # [{'age': 12, 'name': 'Mike'}, {'age': 29, 'name': 'John'}, {'age': 40, 'name': 'Bill'}]
print(sorted(a,key=lambda x:x['age'],reverse=True)) # [{'age': 40, 'name': 'Bill'}, {'age': 29, 'name': 'John'}, {'age': 12, 'name': 'Mike'}]

13. 字典键值支持哪些数据类型

1. 有哪些数据类型不能作为字典键值的类型

列表和字典

2. 为什么列表和字典类型的值不能作为字典的键值

因为key是不能变的,列表和字典的值是可以变化的。一旦变化就找不到value。
列表和字典无法哈希(unhashable)

14. 如何对生成器类型的对象使用切片

1. 我们知道使用切片可以获取列表的部分元素,那么如何使用切片获取生成器类型对象的部分元素呢?

from itertools import islice

gen = iter(range(10))
print(type(gen))

for i in islice(gen,2,7):
	print(i)

15. 将循环参数的列表变成生成器

1. 如何将[i for i in range(20)]变成生成器

a = [ i for i in range(10)]

print(a)
print(type(a))

b = (i for i in range(10))
print(b)
print(type(b))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
<type 'list'>
<generator object <genexpr> at 0x0000000002511438>
<type 'generator'>

16. Python字典与Json字符串如何互转

1. Python字典与Json字符串如何互转

d={'a':123,'b':'456','c':'xyz'}
print(d)
print(type(d))

import json

json_str = json.dumps(d)
print(json_str)
print(type(json_str))

d1 = json.loads(json_str)
print(d1)
print(type(d1))
{'a': 123, 'c': 'xyz', 'b': '456'}
<type 'dict'>
{"a": 123, "c": "xyz", "b": "456"}
<type 'str'>
{u'a': 123, u'c': u'xyz', u'b': u'456'}
<type 'dict'>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值