可读性较高的python代码

#列表推导式:
#列表推导式使用场景:
#当需要遍历多次列表,通过满足某些特定条件元素来创建子序列,并且你认为把数据保存在内存中不是问题时,你可以使用列表推导式。
[x**2 for x in range(10)]
[x for x in vec if x >= 0]
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[num for elem in vec for num in elem]
[weapon.strip() for weapon in freshfruit]
[(x, x**2) for x in range(6)]
[str(round(pi, i)) for i in range(1, 6)]
[[row[i] for row in matrix] for i in range(4)]
list(zip(*matrix))


#生成器使用场景:
#文件太大,一次性从数据库中读取大量数据可能会影响内存,并让代码变慢,你需要重构代码为生成器逻辑版本。
def read_file_line(file_name):
        """读取文件并返回文件的每一行.
        @param file_name:文件的绝对路径.
        @return: yiled line.
        """
        with open(file_name) as fread:
            for line in fread:
                yield line


#使用namedtuple作为返回值
#如果Python基础还不错的童鞋,应该知道Python 在return 返回多个值得时候,默认是组成元组进行返回,我们通过返回namedtuple,让返回值更具有可读性,因为namedtuple是tuple元祖的子类,当然包含了它的全部特性,并且有一些元祖没有的额外特性。
#namedtuple是继承自tuple的子类。namedtuple创建一个和tuple类似的对象,而且对象拥有可访问的属性。用以构建只有少数属性但是没有方法的对象。用作返回值很是biu 丢 for !
User = collections.namedtuple('User', ['name', 'age'])
user = User('张三''18')
print(user.name) # 张三
print(user.age) # 18
return user # 可以作为对象进行返回,在传给其他函数的时候,也方便多了。
#使用场景总结:返回多个值,并需要大量传递时,可以使用namedtuple,来减轻参数的数量,让代码可读性更好。如果初学Python不是很懂,代码数量达到一定级别时,回来在思考这个问题,参数的个数,命名,传递的频率,这里就会涉及到考虑升高可读性,扩展性等。

#itertools 模块
#1-输出长度为3的所有子序列
import itertools as it
print(list(it.combinations('1245',3)))
# [('1', '2', '4'), ('1', '2', '5'), ('1', '4', '5'), ('2', '4', '5')]

#2-输出长度为2的所有全排子序列
print(list(it.permutations('124',2)))
# [('1', '2'), ('1', '4'), ('2', '1'), ('2', '4'), ('4', '1'), ('4', '2')]

#3-输出笛卡尔积
print(list(it.product([1,2,3],repeat=2)))
#[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

#4-数据分组
from operator import itemgetter

rows = [
{
    
    'address': '5412 N CLARK', 'date': '07/01/2012'},
{
    
    'address': '5148 N CLARK', 'date': '07/04/2012'},
{
    
    'address': '5800 E 58TH', 'date': '07/02/2012'},
{
    
    'address': '2122 N CLARK', 'date': '07/03/2012'},
{
    
    'address': '5645 N RAVENSWOOD', 'date': '07/02/2012'},
{
    
    'address': '1060 W ADDISON', 'date': '07/02/2012'},
{
    
    'address': '4801 N BROADWAY', 'date': '07/01/2012'},
{
    
    'address': '1039 W GRANVILLE', 'date': '07/04/2012'},
]

for date,items in it.groupby(rows,key=itemgetter('date')):
    print(date)
    for i in items:
        print(" ",i)

猜你喜欢

转载自blog.csdn.net/sasibingdu/article/details/120976315