list comprehensions

列表解释

You now have all the knowledge necessary to begin writing list comprehensions! Your job in this exercise is to write a list comprehension that produces a list of the squares of the numbers ranging from 0 to 9.

Create list comprehension: squares
squares = [i**2 for i in range(0,10)]

nested list comprehensions

[[output expression] for iterator variable in iterable]

writing a list comprehension within another list comprehension, or nested list comprehensions.

# Create a 5 x 5 matrix using a list of lists: matrix
matrix = [[col for col in range(5)] for row in range(5)] # Print the matrix
for row in matrix:
print(row)

you can apply a conditional statement to test the iterator variable by adding an if statement in the optional predicate expression part after the for statement in the comprehension:

通用表达式,这种形式,看别人代码的时候出现很多,确实省代码的


[ output expression for iterator variable in iterable if predicate expression ].
# Create a list of strings: fellowship
fellowship = ['frodo', 'samwise', 'merry', 'aragorn', 'legolas', 'boromir', 'gimli'] # Create list comprehension: new_fellowship
new_fellowship = [member for member in fellowship if len(member) >= 7] # Print the new list
print(new_fellowship) <script.py> output:
['samwise', 'aragorn', 'legolas', 'boromir']

using a list comprehension and an if-else conditional statement in the output expression

输出的结果是一个if-else语句,这样挺直观简单的

# Create a list of strings: fellowship
fellowship = ['frodo', 'samwise', 'merry', 'aragorn', 'legolas', 'boromir', 'gimli'] # Create list comprehension: new_fellowship
new_fellowship = [member if len(member) >= 7 else '' for member in fellowship] # Print the new list
print(new_fellowship)

Dict comprehensions

字典解析

同理字典解析

比较生成器和列表解析的结果

In [1]: # List of strings
... fellowship = ['frodo', 'samwise', 'merry', 'aragorn', 'legolas', 'boromir', 'gimli']
...
... # List comprehension
... fellow1 = [member for member in fellowship if len(member) >= 7] In [2]: fellow2 = (member for member in fellowship if len(member) >= 7) In [3]: fellow1
#很明显,列表解析输出的是一个列表
Out[3]: ['samwise', 'aragorn', 'legolas', 'boromir'] In [4]: fellow2
#生成器就是一个生成器对象
Out[4]: <generator object <genexpr> at 0x7f3821ba3a40>

一个列表解析的小例子

# Extract the created_at column from df: tweet_time
tweet_time = df['created_at'] # Extract the clock time: tweet_clock_time
tweet_clock_time = [entry[11:19] for entry in tweet_time if entry[17:19] == '19'] # Print the extracted times
print(tweet_clock_time)

zip()

  • zip()是可迭代对象,使用时必须将其包含在一个list中,方便一次性显示出所有结果
  • 它可以将多个序列(列表、元组、字典、集合、字符串以及 range() 区间构成的列表)“压缩”成一个 zip 对象。所谓“压缩”,其实就是将这些序列中对应位置的元素重新组合,生成一个个新的元组
# Zip lists: zipped_lists
zipped_lists = zip(feature_names,row_vals) # Create a dictionary: rs_dict
rs_dict = dict(zipped_lists) # Print the dictionary
print(rs_dict)

yeild

生成器的关键字,功能有点类似于return

参考

datacamp上面给的一个实例练习

数据集来自the World Bank's World Development Indicators

通过这个小demo能够更好的理解函数的定义,就是把所有的需求放到一个函数里,想让这个函数通用,那就提取公共的参数,从外面传进去。

# Define lists2dict()
def lists2dict(list1, list2):
"""Return a dictionary where list1 provides
the keys and list2 provides the values.""" # Zip lists: zipped_lists
zipped_lists = zip(list1, list2) # Create a dictionary: rs_dict
rs_dict = dict(zipped_lists) # Return the dictionary
return rs_dict # Call lists2dict: rs_fxn
rs_fxn = lists2dict(feature_names,row_vals) # Print rs_fxn
print(rs_fxn)

python write file

# Open a connection to the file
# 打开一个文件,读出里面的数据
with open('world_dev_ind.csv') as file: # Skip the column names
file.readline() # Initialize an empty dictionary: counts_dict
counts_dict = {} # Process only the first 1000 rows
for j in range(0,1000): # Split the current line into a list: line
line = file.readline().split(',') # Get the value for the first column: first_col
first_col = line[0] # If the column value is in the dict, increment its value
if first_col in counts_dict.keys():
counts_dict[first_col] += 1 # Else, add to the dict and set value to 1
else:
counts_dict[first_col] = 1 # Print the resulting dictionary
print(counts_dict)

自定义一个绘图函数

# Define plot_pop()
def plot_pop(filename, country_code): # Initialize reader object: urb_pop_reader
urb_pop_reader = pd.read_csv(filename, chunksize=1000) # Initialize empty DataFrame: data
data = pd.DataFrame() # Iterate over each DataFrame chunk
for df_urb_pop in urb_pop_reader:
# Check out specific country: df_pop_ceb
df_pop_ceb = df_urb_pop[df_urb_pop['CountryCode'] == country_code] # Zip DataFrame columns of interest: pops
pops = zip(df_pop_ceb['Total Population'],
df_pop_ceb['Urban population (% of total)']) # Turn zip object into list: pops_list
pops_list = list(pops) # Use list comprehension to create new DataFrame column 'Total Urban Population'
df_pop_ceb['Total Urban Population'] = [int(tup[0] * tup[1] * 0.01) for tup in pops_list] # Append DataFrame chunk to data: data
data = data.append(df_pop_ceb) # Plot urban population data
data.plot(kind='scatter', x='Year', y='Total Urban Population')
plt.show() # Set the filename: fn
fn = 'ind_pop_data.csv' # Call plot_pop for country code 'CEB'
plot_pop(fn,'CEB') # Call plot_pop for country code 'ARB' plot_pop(fn,'ARB')

python list comprehensions的更多相关文章

  1. 每天学点Python之comprehensions

    每天学点Python之comprehensions 推导式能够简化对数据的处理,让代码简洁的同一时候还具有非常高的可读性.这在Python中非经常见. 列表推导式 通过列表推导式能够对列表中的全部元素 ...

  2. [翻译]Python List Comprehensions: Explained Visually || Python列表解析式

    原文1地址: http://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/ 原文2地址: http://blog.tea ...

  3. CS224N Assignment1 Section 1

    运行环境需求 # All Import Statements Defined Here # Note: Do not add to this list. # All the dependencies ...

  4. [NLP] cs224n-2019 Assignment 1 Exploring Word Vectors

      CS224N Assignment 1: Exploring Word Vectors (25 Points)¶ Welcome to CS224n! Before you start, make ...

  5. Python基础知识--Slice(切片)和Comprehensions(生成式)

    最近在Youtube的Python视频教程上学习Python相关的基础知识,视频由Corey Schafer制作,讲得十分简单明了,英文发音也比较清晰,几乎都能听懂,是一个不错的Python入门学习的 ...

  6. Python中的Comprehensions和Generations

    Python中的Comprehensions和Generations语法都是用来迭代的.Comprehensions语法可用于list,set,dictionary上,而Generations语法分为 ...

  7. [Python's] Python's list comprehensions a

    # Python's list comprehensions are awesome. vals = [expression for value in collection if condition] ...

  8. [Python] 字典推导 PEP 274 -- Dict Comprehensions

    之前自己也遇到过一次,这段时间在群里也遇到过几次的一个问题 用python2.7写的一段程序.里面用到了字典推导式,可是server版本号是python2.6,无法执行. 今天查了下关于Dict Co ...

  9. Python高级特性——列表生成式(list Comprehensions)

    List Comprehensions 即列表生成式,是Python内置的强大的用来生成列表list的生成式. 简单菜: >>> l = list(range(2,13)) > ...

随机推荐

  1. 并发编程之Master-Worker模式

    我们知道,单个线程计算是串行的,只有等上一个任务结束之后,才能执行下一个任务,所以执行效率是比较低的. 那么,如果用多线程执行任务,就可以在单位时间内执行更多的任务,而Master-Worker就是多 ...

  2. VFP 图形文件与剪切板互换的API解决方法

    在 VFP 中,凡遇图形处理,大多数情况下,都会涉及到图形文件与剪切板互换的情况.下面给出利用 API 解决的方法.这是原来从网上摘下来的,版权归原作者.基本处理的代码如下,你可以将其应用到你的代码中 ...

  3. 数据算法 --hadoop/spark数据处理技巧 --(5.移动平均 6. 数据挖掘之购物篮分析MBA)

    五.移动平均 多个连续周期的时间序列数据平均值(按相同时间间隔得到的观察值,如每小时一次或每天一次)称为移动平均.之所以称之为移动,是因为随着新的时间序列数据的到来,要不断重新计算这个平均值,由于会删 ...

  4. Linux的那些事-系统启动(增加开机启动项)

    1   /etc/init.d 2   /etc/inittab 3   /etc/rc.d/init.d  1.   /etc/init.d 是一般开机的启动服务存放在这个目录下,至于实现机制,其实 ...

  5. clr via c# clr寄宿和AppDomain (一)

    1 clr寄宿-----.net framework在windows平台的顶部允许.者意味着.net framework必须用windows能理解的技术来构建.所有托管模块和程序集文件必须使用wind ...

  6. UI自动化技术在高德的实践

    一.背景汽车导航作为ToB业务,需要满足不同汽车厂商在功能和风格上体现各自特色的需求.针对这种情况,传统的UI开发方式,基本上是一对一的特别定制.但是这种方式动辄就要500~600人日的工作量投入,成 ...

  7. JavaScript之if流程控制演练,if写在区间内怎么解决

    什么是编程?通俗意见上来讲,就是把人的思维与步骤通过代码的形式书写展示出来,JavaScript的流程控制包含条件判断if,switch选择,循环for while:if(表达式 条件)=>真{ ...

  8. 如何在IDEA的maven项目中连接并使用MySQL8.0

    首先看一下我的基本的开发环境: 操作系统:MacOS 10.13.5 编辑器:IDEA 2018.3 其他:MySQL8.0.15.Maven 3.3.9.JDK 1.8 好,下面就正式开始: 第一步 ...

  9. Oracle的overlaps函数转换其他数据库语法

    首先,来介绍一下Oracle的overlaps函数的用法: overlaps函数是用来判断两个时间段是否有重叠的 比如说计算 (a,b),(c,d) 就可以写成: select * from dual ...

  10. Markdown语法,及其在typora中的快捷键,学写博客吧!!!

    前言 Markdown (MD) 是现在最流行的一种文档书写语言格式.平常写笔记,写博客,写计划再好不过了.个人觉得使用很简单,右击鼠标,有你想要的操作. Typora是简洁.操作简单.功能强大.方便 ...