除了if…else进行条件判断外,还有谁
见识下方括号[] 的魅力
s = 'cofjdDWS'
# 查看字符串中大小写英文字符哪个多
upper = sum(c.isupper() for c in s)
lower = sum(c.islower() for c in s)
print(upper) # sum(False)=0
print(lower)
result = [s.lower(), s.upper()][upper < lower] # 第二个方括号为真,则执行第一个方括号的第二个函数!!!
print(result)
3
5
COFJDDWS
方括号[] 的妙用2
"""
列出1到20的数字,
若是3的倍数就用apple代替,
若是5的倍数就用orange代替,
若既是3的倍数又是5的倍数就用appleorange代替
"""
import heapq
from collections import namedtuple
print(['apple'[i % 3 * 5::] + 'orange'[i % 5 * 6::] or i for i in range(1, 21)])
# input result
# [1, 2, 'apple', 4, 'orange', 'apple', 7, 8, 'apple', 'orange',
# 11, 'apple', 13, 14, 'appleorange', 16, 17, 'apple', 19, 'orange']
分析: ‘apple’[i%3*5::]: 从i(包括)开始切到最后
后面的5主要是取余后要么等于0,要么等于从1~4,乘以5之后,都切不到字符串 最后的or
是那三种情况都不满足情况下,就直接显示当前循环变量i
推导列表生成字典
my_list = [(1, 'a'), (2, 'b')]
print({x[0]: x[1] for x in my_list})
# input result
# {1: 'a', 2: 'b'}
print({index: x for index, x in enumerate('abcd')})
# input result
# {0: 'a', 1: 'b', 2: 'c', 3: 'd'}
漂亮的zip生成
print(dict(zip('abcd', range(10))))
# input result
# {'a': 0, 'b': 1, 'c': 2, 'd': 3}
chinese = [90, 70, 96]
eng = [80, 78, 90]
math = [96, 84, 80]
total = []
for c, e, m in zip(chinese, eng, math):
total.append(c + e + m)
print(total)
# input result
[266, 232, 266]
能不能直接写成if
# if val is not None
# if val ,其中的val可以是'',0,None,[],{}
给list分组该咋整
a = [3, 8, 9, 4, 1, 10, 6, 7, 2]
list(a[i:i + 3] for i in range(0, len(a), 3))
# input result
# [[3, 8, 9], [4, 1, 10], [6, 7, 2]]
套娃也有春天,如何一个个取出来
"""
比如有一个嵌套的列表,里面嵌套了很多层,
有列表有元组,层层嵌套,
如何把它转换成只有一层的列表,必须要用递归也能解决
"""
cascade = [1, [2], [3, [4, [10, [34, 53]]]], (6, 98)]
stream = []
def flat(seq):
for each in seq:
if isinstance(each, list) or isinstance(each, tuple):
flat(each)
else:
stream.append(each)
flat(cascade)
print(stream)
# result
# [1, 2, 3, 4, 10, 34, 53, 6, 98]
查询列表里面的某一个值
landscape = ['bog', 'cave', 'cliff', 'coast', 'desert', 'jungle']
list(filter(lambda x: x.startswith('c'), landscape))
# result
# ['cave', 'cliff', 'coast']
用namedtuple玩一玩扑克牌
# ranks: 数字 suits:花色
Card = namedtuple('Card', ['rank', 'suit'])
c = Card('7', 'diamonds')
print(c) # Card(rank='7', suit='diamonds')
class FrenchDeck:
ranks = [str(n) for n in range(2, 11)]
ranks = ranks + list('JQKA')
suits = 'spades diamonds clubs hearts'.split()
def __init__(self):
self._cards = [Card(rank, suit) for suit in self.suits
for rank in self.ranks]
def __len__(self):
return len(self._cards)
def __getitem__(self, position):
return self._cards[position]
f1 = FrenchDeck()
print(f1._cards)
print(f1.__len__())
print(f1.__getitem__(3)) # 下标从0开始
# result
# [Card(rank='2', suit='spades'), Card(rank='3', suit='spades')...]
根据字典中的某一个子元素,进行排序
nums = [19, 3, 13, 54, 89]
print(heapq.nlargest(3, nums))
print(heapq.nsmallest(3, nums))
# [89, 54, 19]
# [3, 13, 19]
students = [
{'weather': 'breeze', 'score': 100, 'height': 190},
{'weather': 'chilly', 'score': 160, 'height': 130},
{'weather': 'breeze', 'score': 120, 'height': 167},
{'weather': 'breeze', 'score': 110, 'height': 128},
]
result = heapq.nsmallest(2, students, key=lambda x: x['height'])
print(result)
# [{'weather': 'breeze', 'score': 110, 'height': 128},
# {'weather': 'chilly', 'score': 160, 'height': 130}]
globals() 和locals()
# a=1
# g={'a':23}
# print(eval('a+1',g))
# Eval: Evaluate the given source in the context of globals and locals.
# In conclude, 我在命令行模式下输出g, 其打印结果和globals() 一致
z=0
def f():
z = 1
print (locals())
locals()["z"] = 2
print (locals())
f()
print(globals()['z'])
globals()["z"] = 2
print (z)
# ---->
# {'z': 1}
# {'z': 1}
# 0
# 2
In conclude, locals()对象的值不能修改,globals()对象的值可以修改
神奇的None 君
s='abc'
for i in [None]+list(range(-1,-len(s),-1)):
print(type(i))
print(s[:None])
<class 'NoneType'>
<class 'int'>
<class 'int'>
abc
--------------------------------------------
s='abc'
for i in list(range(-1,-len(s))): # 没有遍历到对象
print(type(i))
for i in [None]+list(range(-1,-len(s))): # 没有遍历到对象
print(type(i)) # <class 'NoneType'>
set的神奇去重排序–底层是红黑树,效率太低
列表去重
实现思路(利用排好序的列表相同元素相邻):
1.对列表原地更新排序
2.逆序遍历列表,比较last和每个遍历元素
3.如果相等,删掉遍历元素
4.如果不相等,将该元素赋值给last
a = [1, 2, 4, 2, 4, 5, 7, 10, 5, 5, 7, 8, 9, 0, 3]
a.sort()
last = a[-1]
for i in range(len(a) - 2, -1, -1):
if last == a[i]:
del a[i]
else:
last = a[i]