一:list和dict的常用的遍历
#遍历list
for item in l:
pass
#通过索引遍历list
way1:
for index in range(0, len(l)):
print(l(index))
way2:
index = 0
while index < len(l):
print(l[index])
index += 1
#通过enumerate()遍历list
for index, item in enumerate(l):
print("index:{}, item:{}".format(index, item))
#遍历dict的key
for key in d:
pass
#遍历dict的值
for v in d.values():
pass
#遍历dict的键值对
for k, v in d.items():
pass
二:if-else的一些用法
一:
expression1 if condition else expression2 for item in iterable
相当于:
for item in iterable:
if condition:
expression1
else:
expression2
example1:
y = [2 * x if x > 0 else -2*x for x in nums]
example2:
场景:将文本作以下操作:
1:按逗号分割;2:去掉长度小于3的单词;3:去掉空格。
text = ' Today, is, Sunday'
text_list = [s.strip() for s in text.split(',') if len(s.strip()) > 3]
print(text_list)
['Today', 'Sunday']
二:
[(x,y) for x in x_nums for y in y_nums]
相当与:
l=[]
for x in x_nums:
for y in y_nums:
l.append((x,y))