python性能优化摘录(二) 分类: python 20130118 11:27 291人阅读 评论(0) 收藏

for i in range(1,10):
    print i,

t=[1,2,3,4,5,2,3]

a=(i for i in t)

print a

#输出结果:<generator object <genexpr> at 0x03ED8670>



s = (i for i in [1, 2, 3, 4, 5])
print s.next()
#输出结果:1

some_list=[1,2,3,4,5,2,3,7,8,4,9]
#列表集合
another_list=[x+1 for x in some_list]

print another_list


#创建集合和字典表


#set comprehensions   集合解析使用{}

ds={x for x in some_list if x%3==0}

print ds

#输出结果:set([9, 3])


#dictionary comprehension 字典集合
d={x: x%2==0 for x in range(1,11)}

print d

#在字典表的例子里,我们创建了一个key是不重复的110之间的整数,value是布尔型,用来指示key是否是偶数。

#结果:{1: False, 2: True, 3: False, 4: True, 5: False, 6: True, 7: False, 8: True, 9: False, 10: True}

#关于集合,对元素进行去重
my_set={1,2,1,2,3,4}

print my_set

#结果:set([1, 2, 3, 4])


#set()内置函数可以将列表、字符串、元组去重

print set(('a','b','d','a'))

#结果:set(['a', 'b', 'd'])


使用Dictionary comprehensions/Set comprehensions

大多数的Python程序员都知道且使用过列表推导(list comprehensions)。如果你对list comprehensions概念不是很熟悉——一个list comprehension就是一个更简短、简洁的创建一个list的方法。

>>> some_list = [1, 2, 3, 4, 5]

>>> another_list = [x + 1 for x in some_list]

>>> another_list

>>> [2, 3, 4, 5, 6]

自从python 3.1 (甚至是Python 2.7)起,我们可以用同样的语法来创建集合和字典表:

>>>#Set Comprehensions

>>> some_list = [1, 2, 3, 4, 5, 2, 5, 1, 4, 8]

>>> even_set = { x for x in some_list if x % 2 == 0 }

>>> even_set set([8, 2, 4])

>>> # Dict Comprehensions

>>> d = {x: x % 2 == 0 for x in range(1, 11)}

>>> d {1: False, 2: True, 3: False, 4: True, 5: False, 6: True, 7: False, 8: True, 9: False, 10: True}

在第一个例子里,我们以some_list为基础,创建了一个具有不重复元素的集合,而且集合里只包含偶数。而在字典表的例子里,我们创建了一个key是不重复的1到10之间的整数,value是布尔型,用来指示key是否是偶数。

这里另外一个值得注意的事情是集合的字面量表示法。我们可以简单的用这种方法创建一个集合:

>>> my_set ={1, 2, 1, 2, 3, 4}

>>> my_set

set([1, 2, 3, 4])

而不需要使用内置函数set()


原文地址:https://www.cnblogs.com/think1988/p/4628250.html