码迷,mamicode.com
首页 > 编程语言 > 详细

Python的一些小技巧

时间:2014-11-14 22:24:52      阅读:323      评论:0      收藏:0      [点我收藏+]

标签:io   for   数据   on   ad   tt   python   c   app   

#coding:utf-8

#数据交换
x = 6
y = 5
x, y = y, x
print x
print y

#相当于:?
print "hello" if False else "world"

#一种方式绑定不同类型的数据
nfc = ["Packers", "49ers"]
afc = ["Ravens","Patriots"]
print nfc + afc
print str(1)+"world"
print ‘1‘+"world"
print nfc,1

#注意浮点除法
print 5.0/2
print 2**5
print .3/.1
print .3//.1

#数值比较 特别棒
x = 2
if 3>x>1:
print x
if 1<x>0:
print x
#同时迭代两个列表
one = [‘Packers‘,‘atteck‘]
two = [‘reaf‘,‘dedad‘]
for a,b in zip(one,two):
print a + " vs. "+b
#带索引的列表迭代
teams = [‘one‘,‘two‘,‘three‘,‘four‘]
for index,team in enumerate(teams):#enumerate枚举列举
print index,team

#过滤出偶数
numbers = [1,2,3,4,5,6,7]
even = []
for number in numbers:
if number%2 == 0 :
even.append(number)
print even
even2 = [number for number in numbers if number%2==0]
print even2

#字典
teams = [‘onee‘,‘two‘,‘three‘,‘four‘,‘five‘,‘six‘]
print {key:value for key,value in enumerate(teams)}#注意是根据for后面的顺序展示
#初始化列表
items = [0]*3
print items

#列表转换为字符串
teams = [‘one‘,‘two‘,‘three‘,‘four‘,‘five‘,‘six‘]
print teams
print ", ".join(teams)

#从字典中获取元素
data = {‘admin‘:1,‘name‘:‘Max‘,‘three‘:4}
a = data.get(‘admin‘,False)
print a
try:
is_admin = data[‘name‘]
except KeyError:
is_admin = False
print is_admin

#获取列表的子集
x = [1,2,3,4,5,6,7]
print x[:3]
print x[1:3]
print x[-5:]
print x[1::2]

#3的倍数打印fizz 5的倍数打印buzz 两者的倍数打印fizzbuzz
for x in range(101):print "fizz"[x%3*4::] + "buzz"[x%5*4::] or x

#迭代工具 随机组合
from itertools import combinations
teams = [‘one‘,‘two‘,‘three‘,‘four‘]
for game in combinations(teams,2):
print game

Python的一些小技巧

标签:io   for   数据   on   ad   tt   python   c   app   

原文地址:http://www.cnblogs.com/Alexander11/p/4098201.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!