"""
python的set和其他语言类似, 是一个无序不重复元素集,
基本功能包括关系测试和消除重复元素.
集合对象还支持union(联合), intersection(交), difference(差)和sysmmetric difference(对称差集)等数学运算.
sets 支持 x in set, len(set),和 for x in set。
作为一个无序的集合,sets不记录元素位置或者插入点。
因此,sets不支持 indexing, slicing, 或其它类序列(sequence-like)的操作。
"""
#----------------------------------------------------
#声明一个列表,找到2的倍数,然后与2相乘
numbers = [1,2,3,4,5]
#普通方法:
doubuled_odds = []
for n in numbers:
if n %2 == 1:
doubuled_odds.append(n * 2)
print 'Normal way: {}'.format(doubuled_odds)
#优雅方法:
doubuled_odds = [n * 2 for n in numbers if n %2 ==1]
print 'Elegant way: {}'.format(doubuled_odds)
#----------------------------------------------------
#
#普通方法:
flattened = []
for row in matrix:
for n in row:
flattened.append(n)
#优雅方法:
flattened = [n for row in matrix for n in row]
#----------------------------------------------------
# 获取获取列表中各字符串的首字母
words = ['11','22','33','44','55','66','77']
words = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
#普通方法:
first_letters = set()
for w in words:
first_letters.add(w[0])
#优雅方法:
first_letters = {w[0] for w in words}
#----------------------------------------------------
# 字典的key与value交换
original = {'name': 'xuejianhui', 'age': 27}
#普通方法:
flipped = {}
for key, value in original.items():
flipped[value] = key
#优雅方法:
flipped = {value : key for key, value in original.items()}
#----------------------------------------------------
#
#普通方法:
new_things = []
for ITEM in old_things:
if condition_based_on(ITEM):
new_things.append("something with " + ITEM)
#优雅方法:
new_things = [
"something with " + ITEM
for ITEM in old_things
if condition_based_on(ITEM)
]
python优雅编程技巧
最新推荐文章于 2024-04-27 03:32:16 发布