#默认值
words =['apple','bat','bar','atom','book']
by_letter ={}for word in words:
letter = word[0]if letter notin by_letter:
by_letter[letter]=[word]else:
by_letter[letter].append(word)
by_letter
#嵌套列表推导式
all_data =[['John','Emily','Michael','Mary','Steven'],['Maria','Juan','Javier','Natalia','Pilar']]
result =[name for names in all_data for name in names
if name.count('e')>=2]
result
['Steven']
some_tuples =[(1,2,3),(4,5,6),(7,8,9)]
flatted =[x for tup in some_tuples for x in tup]
flatted
[1, 2, 3, 4, 5, 6, 7, 8, 9]
#函数#变量的命名空间,作用域,局部函数#返回多个值#函数也是对象
states =[' Alabama ','Georgia!','Georgia','georgia','FlOrIda','south carolina##','West virginia?']
import re
defremove_punctuation(value):return re.sub('[!#?]','',value)
clean_ops =[str.strip,remove_punctuation,str.title]defclean_string(strings,ops):
result =[]for value in strings:for function in ops:
value = function(value)
result.append(value)return result
clean_string(states,clean_ops)
#迭代器
some_dict ={'a':1,'b':2,'c':3}for key in some_dict:print(key)
a
b
c
dict_iterator =iter(some_dict)
dict_iterator
<dict_keyiterator at 0x1a2dfdfe228>
list(dict_iterator)
['a', 'b', 'c']
#生成器defsquares(n=10):print('Generating squares from 1 to {0}'.format(n**2))for i inrange(1,n+1):yield i**2
gen = squares()
gen
<generator object squares at 0x000001A2DFDBF750>
for x in gen:print(x,end=" ")
Generating squares from 1 to 100
1 4 9 16 25 36 49 64 81 100
#生成器表达式
gen =(x**2for x inrange(100))
gen
<generator object <genexpr> at 0x000001A2DFDBF930>
sum(x**2for x inrange(100))
328350
dict((i,i**2)for i inrange(5))
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
#itertools模块import itertools
first_letter =lambda x :x[0]
names =['Alan','Adam','Wes','Will','Albert','Steven']for letter,names in itertools.groupby(names,first_letter):print(letter,list(names))
A ['Alan', 'Adam']
W ['Wes', 'Will']
A ['Albert']
S ['Steven']
#错误和异常处理float('something')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-52-588ffff62dd7> in <module>()
1 #错误和异常处理
----> 2 float('something')
ValueError: could not convert string to float: 'something'
defattempt_float(x):try:returnfloat(x)except:return x
attempt_float('something')
'something'
float((1,2))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-54-a101b3a3d6cd> in <module>()
----> 1 float((1,2))
TypeError: float() argument must be a string or a number, not 'tuple'
defattempt_float(x):try:returnfloat(x)except(TypeError, ValueError):return x
attempt_float((1,2))