python中三目运算符、推导式 ## 17

三目运算符是精简代码的优化手段,在一定场景可以适用
比如下面给大家举个例子

  • 例1:
score = 89
print("A" if score > 80 else "C")
  • for循环遍历字符串
str_code = "hello world"
for s in str_code:
    print(s)
h
e
l
l
o
 
w
o
r
l
d
  • for循环遍历列表
list_language = ["python","C++", "GO"]
for l in list_language:
    print(l)
python
C++
GO
  • 打印0-100 之间所有数字的方法
for number in range(0,101):
    print(number)
  • 遍历列表里的值打印索引及每个元素对应的具体值是多少,你会想起有几种方法呢?

当然听到这个问题,我们脑海中一闪而过的应该是下面这种方法,通过len()获取列表的长度,然后通过指定索引获取到对应元素的值

list_language = ["python","C++", "GO"]

for i in range(len(list_language)):
    print(i, list_language[i])

除了上面的方法,我们还可以通过下面的enumerate()方法来实现

for key, value in enumerate(list_language):
    print(key,value)
0 python
1 C++
2 GO

这两种方法是等价的,推荐第二种,enumerate() 这种方法的性能更高

  • while循环是不知道要循环多少次的,一定要设计退出循环的条件,否则就会死循环
  • continue 是退出本次循环,break是退出整个循环

推导式

列表推导式

  • 例1:
    创建一个列表,里面存放1-100之间的数,用列表推导式来实现
list01 = [i for i in range(0, 101)]
print(list01)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
  • 例2:在1-100的列表基础上每个元素乘以2
list01 = [i*2 for i in range(0, 101)]
print(list01)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 118, 120, 122, 124, 126, 128, 130, 132, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 154, 156, 158, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 182, 184, 186, 188, 190, 192, 194, 196, 198, 200]
  • 例3:列表推导式集成了分支判断
list01 = [i*2 for i in range(0, 101) if i<6]
print(list01)
[0, 2, 4, 6, 8, 10]
  • 例4:列表推导式返回值可以任意
list01 = ["mily" for i in range(0, 101) if i<6]
print(list01)
['mily', 'mily', 'mily', 'mily', 'mily', 'mily']

字典推导式

  • 例1:将字典里的key和value值对调位置
dict1 = {"a":1, "b":2,"c":3}
dict2 = {value:key for key,value in dict1.items()}
print(dict2)
{1: 'a', 2: 'b', 3: 'c'}
  • 例2:将对调后的key值乘以2
dict1 = {"a":1, "b":2,"c":3}
dict2 = {value*2:key for key,value in dict1.items()}
print(dict2)
{2: 'a', 4: 'b', 6: 'c'}

集合推导式

  • 例1:将列表里的值去重
list1 = [1,2,3,4,1,2,5]
set1 = {i for i in list1}
print(set1)
{1, 2, 3, 4, 5}
  • 例2:将列表里的值去重,结果乘以2
list1 = [1,2,3,4,1,2,5]
set1 = {i*2 for i in list1}
print(set1)
{2, 4, 6, 8, 10}

一分耕耘一分收获,不忘初心,加油,mily~

你可能感兴趣的:(python,python,开发语言)