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

Python基础语法二

2017-09-08 15:21 405 查看
1. 数据结构

################################################################

# 元组:()就代表元组,只读列表
aTuple = ('robert', 77, 93, 'try')
print aTuple[1:3]
aTuple[1] = 5  # 报错:'tuple' object does not support item assignment

################################################################

# 列表:[]就代表列表
aList = [1, 2, 3, 'a String']
print aList[0]
print aList[2:]
print aList[:3]
aList[1] = 5
print aList

结果:
1
[3, 'a String']
[1, 2, 3]
[1, 5, 3, 'a String']

################################################################

# 字典:{}就代表字典,类似于Java的Map
aDict = {'host': 'earth'}
aDict['port'] = 80
aDict[None] = None
aDict[None] = 8088
aDict[1] = 9
print aDict
print aDict.keys()
print aDict.values()
print aDict['host']

结果:
{1: 9, 'host': 'earth', 'port': 80, None: 8088}
[1, 'host', 'port', None]
[9, 'earth', 80, 8088]
earth

################################################################

# 遍历字典
for key in aDict:
print key, aDict[key]
# 遍历字典且打印出索引
for i, key in enumerate(aDict):
print i, key, aDict[key]

结果:
1 9
host earth
port 80
None 8088
0 1 9
1 host earth
2 port 80
3 None 8088

################################################################

# 删除键值对
del aDict[1]
print aDict

结果:
{'host': 'earth', 'port': 80, None: 8088}


2. 批量重命名

# coding=utf-8

import os
import shutil # 封装了shell中的一些命令

d = 'E:\\workspace\\Python\\HelloPython\\file'
# 遍历路径下的文件,i代表每个文件的文件名
for i in os.listdir(d):
new_file = i.replace("part", "part-r-000")
old_full_file = d + '\\' + i
new_full_file = d + '\\' + new_file
shutil.move(old_full_file, new_full_file)

print 'Done!'






Linux中写python脚本来批量重命名

#!/usr/bin/python
# coding=utf-8

import os
import shutil

d = '/tmp/'
# 遍历路径下的文件,i代表每个文件的文件名
for i in os.listdir(d):
# 在Linux中,没有IDE提示,必须保证缩进是4个空格
new_file = i.replace("part", "part-r-000")
old_full_file = d + '\\' + i
new_full_file = d + '\\' + new_file
shutil.move(old_full_file, new_full_file)
print 'Done!'

执行python脚本的命令:python change_filenames.py


3.常用方法

# coding=utf-8

################################################################

import sys
# 查看数据类型或者模块中有哪些属性和方法
print dir(sys)

################################################################

# 查看帮助(需要在命令行执行)
help("keywords")
# 查看import关键字如何使用
help("import")
# 查看模块的使用
help("os.path")
# 查看list如何使用
help("list")
# 查看字符串中find方法使用
4000
help("str.find")
# 查看内置函数如何使用
help("open")

################################################################

# 字符串数字之间转换
print int("6")
print str(6)

################################################################

# 字符串长度
foo = 'abc'
print len(foo)

################################################################

# open()打开文件操作
poem = '让我们一起学习Python!'
# a : append(写文件:追加)
# w : write(写文件:覆盖)
# r : read(只读)
f = open('file/test.txt', 'a')
f.write('\n' + poem)
f.close()

################################################################

# range()一组数字
print range(10)
print range(1,10,3) # 步长为3
# 遍历字符串
foo = 'abc'
for i in range(len(foo)):
# %d用来输出10进制整数
print foo[i], '(%d)' % i

结果:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 4, 7]
a (0)
b (1)
c (2)

################################################################

# enumerate()
aDict = {'host': 'earth'}
aDict['port'] = 80
for i, key in enumerate(aDict):
print i, key, aDict[key]

结果:
0 host earth
1 port 80

################################################################

# type()获得对象类型,isinstance()判断数据类型
print type(aDict)
print isinstance(6, int)
print isinstance(aDict, dict)
print isinstance(aDict, list

结果:
<type 'dict'>
True
True
False

################################################################

# 删除元素
aList = [1,2,3]
print aList
del aList[1]
print aList

结果:
[1, 2, 3]
[1, 3]

################################################################

# lambda表达式
data = []
data.append({"name": "Jed", "age": 20, "salary": 3500, "height": 175})
data.append({"name": "Jack", "age": 20, "salary": 3000, "height": 185})
data.append({"name": "Bob", "age": 30, "salary": 6000, "height": 170})
# sort排序:
# key指定按照哪个key来排序
# y没有实际意义,类似于Java定义方法时的参数名,这里指data中的每个元素,即字典
# 先按照age排序,如果age相同,按照height排序
# reverse=True设置为降序展示
data.sort(key=lambda y: (y['age'], y['height']), reverse=True)
for d in data:
print d

结果:
{'salary': 6000, 'age': 30, 'name': 'Bob', 'height': 170}
{'salary': 3000, 'age': 20, 'name': 'Jack', 'height': 185}
{'salary': 3500, 'age': 20, 'name': 'Jed', 'height': 175}

# -y['height']指定,height字段按照与原来相反的顺序展示
data.sort(key=lambda y: (y['age'], -y['height']), reverse=True)
for d in data:
print d

结果:
{'salary': 6000, 'age': 30, 'name': 'Bob', 'height': 170}
{'salary': 3500, 'age': 20, 'name': 'Jed', 'height': 175}
{'salary': 3000, 'age': 20, 'name': 'Jack', 'height': 185}

################################################################

# WordCount Python版
text_file =spark.textFile("hdfs://...")
text_file.flatMap(lambda line: line.split())
.map(lambda word: (word, 1))
.reduceByKey(lambda a,b: a+b)

################################################################

# 对象比较支持多个比较操作
print 3 < 4 < 7 # 相当于(3<4) and (4<7)
print 4 > 3 == 3 # 相当于(4>3) and (3==3)
print 4 < 3 < 8 != 2 < 7
# 从左到右:相当于(4<3) and (3<8) and (8!=2) and (2<7)

################################################################

# Java中的Collections.reverse(arrayList)
fooList = [123, 'abc', 342.23, 'xyz']
print fooList[::-1] # ['xyz', 342.23, 'abc', 123]
# 反转后按步长为2取值
print fooList[::-2] # ['xyz', 'abc']
# Java中的Collections.sort(arrayList)
print sorted(fooList) # [123, 342.23, 'abc', 'xyz']

################################################################

# 对象比较
foo1 = foo2 = 4.3
print foo1 == foo2 # True
print foo1 is foo2 # True

foo1 = 4.3; foo2 = foo1 # python不习惯写";",但如果两行放在一行,必须写
print foo1 == foo2 # True
print foo1 is foo2 # True

foo1 = 4.3; foo2 = 1.3 + 3.0
print foo1 == foo2 # True
print foo1 is foo2 # False




关于对象比较,想了解更多的朋友可以参考一下:

http://www.cnblogs.com/CheeseZH/p/5260560.html

################################################################

# cmp(a,b) 比较大小,返回-1,0,1
print cmp(7, 7) # 0
print cmp('abs', 'azs') # -1

################################################################

# round() 四舍五入
print round(100.10) # 100.0
print round(100.49) # 100.0
print round(100.50) # 1
aecf
01.0

################################################################

from random import randint
print randint(1, 100) # [1,100)的随机整数

# 导入方法时可以起别名
from random import randint as abc
print abc(1, 100) # 与上面方法是一样的

################################################################

# in 操作,返回True和False
print 'bc' in 'abcd'
print 'n' in 'abcd'
print 'nm' not in 'abcd'

################################################################

# string 模块
import string
# 首字母大写
print string.capitalize("hello") # Hello
# 26个字母的小写形式
print string.lowercase
print "HELLO".lower() # hello
print "hello".upper() # HELLO
# 默认按空格分割
print string.split("asdadada asdada") # ['asdadada', 'asdada']
# 去除右边空格
print string.rstrip("   adsd   ")
# 去除左边空格
print string.lstrip("   adsd   ")
# 去除两边边空格
print string.strip("    ad sd  ")

################################################################

# 正则
# Python提供了两种不同的原始操作:match和search
# match是从字符串的起点开始做匹配,如果不是起始位置匹配成功的话,就返回None
# 而search是从字符串任意位置做任意匹配
# 可以使用group()匹配对象函数来获取匹配表达式

m = re.match('www', 'www.baidu.com')
print m # <_sre.SRE_Match object at 0x0000000002AD54A8>
m = re.match('www', 'www.baidu.com').span()
print m # (0, 3)
m = re.match('com', 'www.baidu.com')
print m # None

# 这种写法与下面的写法作用一样
pattern = re.compile("c")
m = pattern.match("cabcdef")
print m.group() # c
m = re.match("c", "cabcdef")
print m.group() # c

#以(ab,b可以多个)开头
m = re.search("^ab+", "acabbbbcdefg")
print m # None
# 包含(ab,b可以多个)
m = re.search("ab+", "asdfabbbb")
print m # <_sre.SRE_Match object at 0x00000000029E54A8>
print m.group() # abbbb
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python