首页 > 文章列表 > python列表推导式的结构探究

python列表推导式的结构探究

Python 列表推导式
299 2022-08-07

1、列表推导式结构包含在一对方括号中,一个表达式,后面是for子句,然后是零个或多个for或if子句。

2、其结果将是一个新列表,根据for和if子句的内容计算表达式。

实例

from collections import Counter
 
def filter_unique(lst):
  temp_list = []
  for item, count in Counter(lst).items():
    if count > 1:
      temp_list.append(item)
  return temp_list
 
# EXAMPLES
filter_unique([1, 2, 2, 3, 4, 4, 5]) # [2, 4]

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。