4

Python代码阅读(第37篇):获取两个列表中相同的元素

 3 years ago
source link: https://segmentfault.com/a/1190000040982833
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Python 代码阅读合集介绍:为什么不推荐Python初学者直接看项目源码

本篇阅读的代码实现了返回两个列表中相同元素的列表的功能。

本篇阅读的代码片段来自于30-seconds-of-python

similarity

def similarity(a, b):
  return [item for item in a if item in b]

# EXAMPLES
similarity([1, 2, 3], [1, 2, 4]) # [1, 2]

similarity函数接收两个列表,返回由两个列表中的相同元素组成的列表。

函数使用列表推导式,遍历所有a列表中的元素,使用in关键词判断这些元素是否在b列表中存在。


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK