关于List和切片的一些问题?

tech2022-07-29  141

1、如何拼接两个列表?

class_1 = ["张三", "李四"] class_2 = ["王五", "钱六"] # 使用 + 号直接拼接 class_1 = class_1 + class_2 # 使用list.extend()方法 class_1.extend(class_2)

2、如何判断列表为空?

while True: # 学生一个一个走出教室,并报上名字 out_student = class_1.pop() print(f"{out_student}-离开了教室") # 使用len()函数判断列表是否为空 if len(class_1) == 0: print("学生都离开了!") # 直接使用列表进行逻辑判断,在python中False,0,'',[],{},()都可以视为假 if not class_1: break

3、如何反转字符串?

word = "Hello World!!!" # 使用list.reverse()方法 word_list = list(word) word_list.reverse() print("".join(word_list)) # 使用反方向的切片 print(word[::-1])

4、如何用Python实现LeetCode:旋转数组?

array = [-1, 2, 7, -9, 10] def rotate(nums, k): i = k % len(nums) # 使用列表切片的形式 nums[:] = nums[-i:] + nums[:-i] # while i: # i -= 1 # # 使用insert()和pop()方法 # nums.insert(0, nums.pop()) print(nums) rotate(array, 11)
最新回复(0)