Python面試一百題——列表、元組與字典(1)

目錄

  1. 去掉列表或元組中的重複元素
  2. 集合之間的並集與交集
  3. 如何讓兩個列表首尾相連(保留重複的元素值)
  4. 打亂列表元素順序的方式
  5. 單星與雙星運算符的作用
  6. 快速調換字典中的 key 和 value
  7. 將兩個列表或元組合併成一個字典
  8. 列表與元組的差異
  9. 如何對列表進行排序
  10. 如果列表元素是對象,如何排序

01.去掉列表或元組中的重複元素

在這裏插入圖片描述
區別:

  1. 列表可以有重複元素,集合沒有
  2. 集合中的元素與順序無關,列表中的元素與順序有關
#去掉列表(元組)中重複元素
a = [1, 2, 2, 3, 4]
a_result = list(set(a))

總結
在這裏插入圖片描述

02.集合之間的並集與交集

在這裏插入圖片描述
需要注意刪除的元素是否存在

x1 = {1, 2, 3}
x2 = {3, 4, 5}
#並集
print(x1 | x2) # 或者x1.union(x2)
#交集
print(x1 & x2)	# 或者x1.intersection(x2)
#其他操作
print(x1 - x2) # x1.difference(x2) x1中有但x2中沒有
print(x1 ^ x2) # 在x1和x2中不同時都有的

總結
在這裏插入圖片描述

03.如何讓兩個列表首尾相連(保留重複的元素值)

在這裏插入圖片描述

#連接列表:+和extend 	連接元組:+
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]

#差異
'''
1.+不會改變參與連接列表的值,但extend會改變a的值
2.+兩側要麼都是元組要麼都是列表,但列表的extend方法可以將一個元組添加到列表後
'''

總結
在這裏插入圖片描述

04.打亂列表元素順序的方式

在這裏插入圖片描述

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
#方法二
def random_list2(a):
    a_copy = a.copy()
    result = []
    for i in range(0, len(a)):
        index = random.randint(0, len(a_copy) - 1)
        result.append(a_copy[index])
        a_copy.pop(index)
    return result

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
b = random_list1(a)
c = random_list2(a)
print(b)
print(c)

#第二題
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
random.shuffle(a)

總結
在這裏插入圖片描述
這個方法會改變原列表裏的元素順序

05.單星與雙星運算符的作用

在這裏插入圖片描述

#單星(*)
#以元組形式導入,可變參數
#如果最後一個參數不是可變參數,那麼爲可變參數後面的形參指定參數值,必須用命名參數
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'>

#雙星(**)
#以字典形式導入 key 和 value
def fun2(param1, **param2):
    print('param1:', param1)
    print('param2:', param2, type(param2))

fun2(1, a = 2, b = 3, c = 4, d = 5)

param1: 1
param2: {'a': 2, 'b': 3, 'c': 4, 'd': 5} <class 'dict'>

#合併列表和字典
a = [1, 2, 3]
b = [4, 5, 6]

x1 = [a, b]	#[[1, 2, 3], [4, 5, 6]]
x2 = [*a, *b]	#[1, 2, 3, 4, 5, 6]

a = {'A': 1, 'B': 2}
b = {'C': 3, 'D': 4}

x = {**a, **b}	# {'A': 1, 'B': 2, 'C': 3, 'D': 4}

總結
在這裏插入圖片描述

06.快速調換字典中的 key 和 value

在這裏插入圖片描述

a = {'A': 1, 'B': 2}

print({v: k for k, v in a.items()})
{1: 'A', 2: 'B'}

#第二題
a = [i for i in range(101)]

07.將兩個列表或元組合併成一個字典

在這裏插入圖片描述

#列表
a = ['a', 'b']
b = [1, 2]

print(dict(zip(a, b)))
{'a': 1, 'b': 2}
#元組
fields = ('id', 'name', 'age')
records = [['01', 'Bill', '20'], ['02', 'Mike', '30']]
result = []
'''
[
{'id': '01', 'name': 'Bill', 'age': '20'}
{'id': '02', 'name': 'Mike', 'age': '30'}
]
'''

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

總結
在這裏插入圖片描述

08.列表與元組的差異

在這裏插入圖片描述

#4個區別

#1:語法差異
a = (1, 2, 3)
b = [1, 2, 3]

#2:元組是隻讀的,列表可讀寫

#3:
copy_a = tuple(a)
copy_b = list(b)
print(a is copy_a)	# True
print(b is copy_b)	# False

#4:大小不同
print(a.__sizeof__())	#48
print(b.__sizeof__())	#64

總結
在這裏插入圖片描述

09.如何對列表進行排序

在這裏插入圖片描述

#排序列表的方法
a = [3, 2, 5, 6, 7, 9, 11]
a.sort()
print(a)	# [2, 3, 5, 6, 7, 9, 11]

b = [3, 2, 5, 6, 7, 9, 11]
c = sorted(b)
print(b)	# [2, 3, 5, 6, 7, 9, 11]
'''
區別:
1.sort屬於列表方法,sorted是獨立函數
2.sort改變列表本身,sorted返回一個排好序的列表副本
'''

#倒敘排列列表
a.sort(reverse= True)
print(a)

print(sorted(b, reverse= True))

總結
在這裏插入圖片描述

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

在這裏插入圖片描述

#方法一:Magic方法
class MyClass:
    def __init__(self):
        self.value = 0
    #定義大於號
    def __gt__(self, other):
        return self.value > other.value
    '''
    #定義小於號
    def __lt__(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]
print(a)

a.sort()

print(a[0].value)	#10
print(a[1].value)	#20
print(a[2].value)	#30

#方法二:operator模塊
class MyClass:
    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]
print(a)

import operator

a.sort(key= operator.attrgetter('value'))
b = sorted(a, key= operator.attrgetter('value'))

#第一題
print(a[0].value)	#10
print(a[1].value)	#20
print(a[2].value)	#30
print(b[0].value)	#10

#第二題
#Magic方法
class MyClass:
    def __init__(self):
        self.value = 0
    '''
    def __gt__(self, other):
        return self.value > other.value
    '''
    def __lt__(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]
print(a)

a.sort()

print(a[0].value)	#30
print(a[1].value)	#20
print(a[2].value)	#10

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

總結
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章