您的位置:首页 > 编程语言 > Python开发

python-基础入门

2015-10-27 11:27 651 查看
列表
shoplist = ['apple', 'mango', 'carrot', 'banana']
shoplist[2] = 'aa'
del shoplist[0] #删除第一个元素
shoplist.insert('4','www') #在第五个位置插入
shoplist.append('aaa')
shoplist[:-1] # 排除最后一个
'\t'.join(li) # 将列表转换成字符串
sys.path[1:1]=[5] # 在位置1前面插入列表中一个
元组

zoo = ('wolf', 'elephant', 'penguin') #不可变
字典

ab = { 'Swaroop' : 'swaroopch@byteofpython.info',
'Larry' : 'larry@wall.org',
}
ab['c'] = 80 # 添加字典元素
del ab['Larry'] # 删除字典元素
ab.keys() # 查看所有键值
ab.values() # 打印所有值
ab.items() # 返回整个字典列表
流程结构

if判断
if a == b:

print '=='
elif a < b:
print b
else:
print a
fi

while循环

while True:
if a == b:
print "=="
break
print "!="
else:
print 'over'

count=0
while(count<9):
print count
count += 1

for循环

for i in range(1, 5):
print i
else:
print 'over'
文件处理

# 模式: 读'r' 写[清空整个文件]'w' 追加[文件需要存在]'a' 读写'r+' 二进制文件'b' 'rb','wb','rb+'
写文件
i={'ddd':'ccc'}
f = file('poem.txt', 'a')
f.write("string")
f.write(str(i))
f.flush()
f.close()

读文件
f = file('/etc/passwd','r')
c = f.read().strip() # 读取为一个大字符串,并去掉最后一个换行符
for i in c.split('\n'): # 用换行符切割字符串得到列表循环每行
print i
f.close()

读文件1
f = file('/etc/passwd','r')
while True:
line = f.readline() # 返回一行
if len(line) == 0:
break
x = line.split(":") # 冒号分割定义序列
f.close()

读文件2
f = file('/etc/passwd')
c = f.readlines() # 读入所有文件内容,可反复读取,大文件时占用内存较大
for line in c:
print line.rstrip(),
f.close()

读文件3
for i in open('b.txt'): # 直接读取也可迭代,并有利于大文件读取,但不可反复读取
print i,
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 元素