列表(list)推导式
[remove for source in xx_list]或者[remove for source in xx_list if condition]
实例:
names=['Bob','Mark','Mausk','Johndan','Wendy']
new_names=[name.upper() for name in names if len(name)<5]
print(new_names)
即迭代列表names中的name变量,当满足字符长度小于5时,返回。
字典推导式(dict)
字典的形成:创建键值对(默认键吗?)
{key:value_remove for value in collection }或者{key:value_remove for value in collection if condition}
实例:
listcollection=['Google','Amazon','Meta']
#字符串值当做键(key),字符串长度当做值(value)
dict={key:len(key) for key in listcollection}
dict
集合推导式(set)
{ expression for item in Sequence }或者
{ expression for item in Sequence if conditional }
setnew={i**3 for i in (2,3,4)}
setnew
元组推导式()
(expression for item in Sequence )
或
(expression for item in Sequence if conditional )
a=(x for x in range(1,100))
a
#tuple()函数生成元组
tuple(a)
纵向不太好显示,这里我用了*改变为函数参数列表使其横向输出…但意思就变了