
01
引言
之前已经有博客专门介绍了Python中的列表生成式,可能大家还不太擅长。这里推荐八个Python列表生成式的面试题(从简单到困难排序),可以帮助大家提高列表生成式的理解水平。
闲话少说,我们直接开始吧!
02
字符串转整数
【题目描述】
lis = ["1", "2", "3", "4", "5"]
[1, 2, 3, 4, 5]
lis = ["1", "2", "3", "4", "5"]answer = [int(i) for i in lis]print(answer)
03
大于10的数字
【题目描述】
lis = [1,5,13,4,16,7]
我们希望用代码实现列表生成式用以找出上述列表中大于10的数字。即样例的输出如下:
[13, 16]
lis = [1,5,13,4,16,7]answer = [i for i in lis if i>10]print(answer)
04
大于10且整除3的数字
【题目描述】
lis = [1,12,13,14,15,2,3]
[12, 15]
【参考答案】
lis = [1,12,13,14,15,2,3]answer = [i for i in lis if i>10 and i%3==0]print(answer)
05
对列表中的偶数执行加1操作
【题目描述】
lis = [1,2,4,5,7]
[1,3,5,5,7]
提示:可以使用三目运算符
lis = [1,2,4,5,7]answer = [(i+1 if i%2==0 else i) for i in lis]print(answer)
06
包含数字1的数字
【题目描述】
即样例的输出如下:
[1,10,11,12,13,14,15,16,17,18,19,21,31,41,51,61,71,81,91,100]
【参考答案】
answer = [i for i in range(1,101) if "1" in str(i)]print(answer)
07
合并两个列表
【题目描述】
fruits = ["apple", "orange", "pear"]prices = [4,5,6]
我们希望用代码实现列表生成式用以对上述两个列表进行合并,即列表中的元素为 (fruit, price) 形式。即样例的输出如下:
[("apple",4), ("orange",5), ("pear",6)]
【参考答案】
fruits = ["apple", "orange", "pear"]prices = [4,5,6]answer = [(fruit, price) for fruit, price in zip(fruits, prices)]print(answer)
08
根据value对字典排序
【题目描述】
d = {"apple":5, "orange":2, "pear":7, "durian":6}
我们需要实现列表生成式用以对上述字典按 price 对相应的元素进行排序。即样例输出如下:
[("orange",2), ("apple",5), ("durian",6), ("pear",7)]
【参考答案】
d = {"apple":5, "orange":2, "pear":7, "durian":6}answer = sorted([(f,p) for f,p in d.items()], key=lambda x:x[-1])print(answer)
09
求两个列表的元素组合
【题目描述】
fruits = ["apple", "orange", "pear"]recipes = ["pie", "juice"]
我们需要实现列表生成式用以对上述两个列表中的元素求解组合操作。即样例输出如下:
[("apple", "pie"), ("apple", "juice"),("orange", "pie"), ("orange", "juice"),("pear", "pie"), ("pear", "juice")]
【参考答案】
fruits = ["apple", "orange", "pear"]recipes = ["pie", "juice"]answer = [(f,r) for f in fruits for r in recipes]print(answer)
10
总结
本文重点介绍了八个Python列表生成式的面试题,并给出了相应的代码实现,可以加深大家对列表生成式的理解。
您学废了吗?
点击上方小卡片关注我
万水千山总关情,点个在看行不行。

