---
title: "pythonic用法"
author: "hqman"
date: "2011-11-04T14:36:28Z"
tags: ["Pythonic"]
categories: ["编程语言"]
slug: "pythonic"
draft: false
lastmod: "2011-11-04T15:12:28Z"
id: 1235376
url: "https://hqman.iteye.com/blog/1235376"
---

python 语言 倡导 简单 简洁 优美

 

记录一些 Pythonic的用法

 

1:使用TAB 来缩进

 

2：交换2个元素值 a,b=b,a

 

3:  list 元素 字符相加 list1=\['a','b','c']    str1=''.join(list1)

 

4: 打开文件  

  with open('xxx.xx') as fp:

           print fp.readline() 

 

5:输出 数组的 index 和 item    

   for (index,item) in enumerate( lsit):

          print index ,item

 

6: 用百分号 来组装字符串  'my name is  %s' % 'wang kai'

 

 

7: 列表推到 过滤 操作 列表 每个元素

    a\_list=\[1,2,3,4,5,6,7,8]

    b\_list=\[item for item in a\_list:  if item %2 ==0]

 

    \[item \*2  for item in range(1,11)]

 

8: 使用装饰器

def func\_time(func):

def \_wrapper(\*args,\*\*kwargs):

start=time.time()

func(\*args,\*\*kwargs)

print func.\_\_name\_\_,"run:",time.time()-start

return \_wrapper

 

@func\_time

def summ(n):