进阶题目2答案
import random
# 生成5个1-100的随机数
nums = [random.randint(1, 100) for _ in range(5)]
# 对数进行排序
sorted_nums = sorted(nums)
# 打印第二大的数和第二小的数
print("第二大的数是:", sorted_nums[-2])
print("第二小的数是:", sorted_nums[1])
sorted(nums)
对生成的5个数进行排序,返回一个排序后的列表。
sorted_nums[-2]
获取排序后的列表中倒数第二个元素,即第二大的数。
sorted_nums[1]
获取排序后的列表中第二个元素,即第二小的数。
题目3
有个列表 [“hello”, “world”, “csdn”],如何把列表里面的字符串联起来,得到字符串 “hello_world_csdn”?
答案
list_strings = ["hello", "world", "csdn"]
result_string = "_".join(list_strings)
print(result_string)
join()
函数可以将一个字符串列表中的所有元素连接成一个单一的字符串,元素之间由指定的分隔符隔开。
进阶题目3
有个列表 [“hello”, “world”, “csdn”],如何把列表里面的字符串联起来,得到字符串 “hello_csdnworld”?