Python语言精要---上
下面的记录根据:
def isiterable(obj):
try:
iter(obj)
return True
except TypeError:
return False
print(isiterable('a string'))
print(isiterable([1,2,3]))
print(isiterable(5))
#检查对象是不是列表或者数组,要是不是的话,就转换成list
x=1,2,3
print(x)
if not isinstance(x, list) and isiterable(x):
x = list(x)
print(x)
[1, 2, 3]
a=[1,2,3,4]
b = a
print(a is b) #这是创建的引用,是指向同一个对象,所以是True
c = list(a) #会创建新的列,所以a与c不指向相同的列
print(a is not c)
print(a ==c) #但是a与c的内容完全相同
a = None
print(a is None)#这是True的因为,None的实例只有一个
a=b=c=5
d=a+b*c
print(d)
a_list = ['foo',1,[12,34]]
a_list[2] = (5,6)
print(a_list) #['foo', 1, (5, 6)]
a_tuple = (1,2,3,(4,5))
a_tuple[1] = 'four' #TypeError: 'tuple' object does not support item assignment
None | 是Python中的null,这个对象只存在一个实例对象 |
str | 字符串 |
unicode | Unicode字符串 |
float | 双精度浮点数 |
bool | True或者False |
int | 有符号整数,最大值由平台决定 |
long | 任意精度有符号整数,大的int会自动转换为long |
cval = 1+2j
print(cval*(1-2j)) #(5+0j)
a = 'first way to define string'
b = "second way to define string"
c = """
thid way to
define a string
"""
print(a)
print(b)
print(c)
'''
first way to define string
second way to define string
thid way to
define a string
'''
a = "this is an immutable object"
print(a[11])
#a[10] = "f" #TypeError: 'str' object does not support item assignment
b = a.replace('object', "string object")
print(b)
'''
i
this is an immutable string object
a = 5.6
s = str(a)
print(s)
s = 'Python Spark'
s_new = list(s)
print(s_new)
print(s[:3])
print(s_new[:3])
s1 = '12\\34'
print(s1)
s2 = r'this\is \no\sprcial characters \n'
print(s2)
print(s1+s2)
'''
5.6
['P', 'y', 't', 'h', 'o', 'n', ' ', 'S', 'p', 'a', 'r', 'k']
Pyt
['P', 'y', 't']
12\34
this\is \no\sprcial characters \n
12\34this\is \no\sprcial characters \n
def add_and_maybe_multiply(a,b,c=None):
result = a+b
if c is not None:
result = result * c
return result
from datetime import datetime,date,time
dt = datetime(2016,8,24,19,22,33)
print(dt.year)
print(dt.month)
print(dt.day)
print(dt.hour)
print(dt.minute)
print(dt.second)
print(dt.date())
print(dt.time())
print(dt.strftime('%m/%d/%Y %H:%M:%S'))
dt_new = dt.replace(minute = 13, second = 23)
print(dt_new)
dt_sub = dt - dt_new
print(dt_sub)
print(type(dt_sub))
dt_recover = dt + dt_sub
print(dt_recover)
print(type(dt_recover))
'''
2016
8
24
19
22
33
2016-08-24
19:22:33
08/24/2016 19:22:33
2016-08-24 19:13:23
0:09:10
<class 'datetime.timedelta'>
2016-08-24 19:31:43
<class 'datetime.datetime'>
'''
a = 1; b = 7;
c = 8; d = 4;
if(a <b or c > d):
print("Made it")
seq = [1,2,None,4,None,6]
total = 0
for value in seq:
if value is None:
continue
total += value
f = open(path,'w')
try:
write_to_file(f)
except (TypeError,ValueError):
print('Failed')
else:
print("Successed")
finally:
f.close()
print(range(10))
print(range(0,20,2))
seq = [1,2,3,4]
for i in range(len(seq)):
print(seq[i])
x = 5
print('Non-negative' if x >=0 else 'negative')
tuple = 4,5,6
print(tuple)
nested_tuple = (4,5,6),(7,8)
print(nested_tuple) #((4, 5, 6), (7, 8))
print(nested_tuple[0]) #(4,5,6)
print(nested_tuple[0][2])#6
tup = tuple + nested_tuple
print(tup) #(4, 5, 6, (4, 5, 6), (7, 8))
print(tup*2) #(4, 5, 6, (4, 5, 6), (7, 8), 4, 5, 6, (4, 5, 6), (7, 8))
#这里元素不可变,一旦创建每个槽的元素不能再修改了。上面的加倍其实只是对象的引用加倍,本身不会被复制
tuple = (1,2,(3,4))
a,b,c = tuple
print(a)
print(c)
d,e,(f,g) = tuple
print(f)
print(g)
'''
1
(3, 4)
3
4
'''
tuple = (1,2,2,2,2,5,6,7,8)
print(tuple.count(2))
a_list = [2,3,5,7,None]
print(a_list)
tuple = ('jason','peggy','thea')
b_list = list(tuple)
print(b_list)
b_list[2] = "cathy"
print(b_list)
'''
[2, 3, 5, 7, None]
['jason', 'peggy', 'thea']
['jason', 'peggy', 'cathy']
'''
b_list.append(a_list)
print(b_list)
b_list.insert(3, 'thea')
print(b_list)
print(b_list.pop(4))
print(b_list)
b_list.append("thea")
print(b_list)
b_list.append("peggy")
print(b_list)
b_list.remove("peggy") #按照值的移除,移除掉第一个出现的位置
print(b_list)
print('peggy' in b_list)
'''
['jason', 'peggy', 'cathy', [2, 3, 5, 7, None]]
['jason', 'peggy', 'cathy', 'thea', [2, 3, 5, 7, None]]
[2, 3, 5, 7, None]
['jason', 'peggy', 'cathy', 'thea']
['jason', 'peggy', 'cathy', 'thea', 'thea']
['jason', 'peggy', 'cathy', 'thea', 'thea', 'peggy']
['jason', 'cathy', 'thea', 'thea', 'peggy']
True
'''
print(a_list)
print(b_list)
c_list = a_list+b_list
print(c_list)
d_list = c_list.extend([7,8])
print(d_list)
#extend耗费的资源更小,因为+是创建新的list将原来的拷贝过去,而extend 只是添加到现有列表
everything = []
for chunk in list_of_lists:
everything.extend(chunk)
everything =[]
for chunk in list_of_lists:
everything = everything = chunk
a = [6,3,2,6,7,2,8,9,3,2]
print(a.sort(key=None, reverse=False))
b = ['charles','jason','peggy','thea']
print(b.sort(key=len, reverse=False))
import bisect
c = [1,2,3,4,5,6,8,9]
print(bisect.bisect(c,7))
bisect.insort(c,7)
print(c)
'''
6
[1, 2, 3, 4, 5, 6, 7, 8, 9]
'''
seq = [4,6,2,6,889,2,57,2,1,57,223]
print(seq[1:5])
seq[1:2] =[99,99]
print(seq)
print(seq[:5])
print(seq[3:])
print(seq[-4:])
print(seq[-6:-2])
print(seq[::2]) #每两个取一个
print(seq[::-1]) #反序
'''
[6, 2, 6, 889]
[4, 99, 99, 2, 6, 889, 2, 57, 2, 1, 57, 223]
[4, 99, 99, 2, 6]
[2, 6, 889, 2, 57, 2, 1, 57, 223]
[2, 1, 57, 223]
[2, 57, 2, 1]
[4, 99, 6, 2, 2, 57]
[223, 57, 1, 2, 57, 2, 889, 6, 2, 99, 99, 4]
'''
some_list = ['charles','peggy','jason']
mapping = dict((v,i) for i,v in enumerate(some_list))
print(mapping)
print(sorted(zip(mapping.keys(),mapping.values()))) #反转排序
print(sorted(zip(mapping.values(),mapping.keys()))) #反转排序
print(sorted([7,2,4,76,9,3,1])) #排序
print(sorted('hello world')) #排序
print(sorted(set('hello world'))) #返回唯一元素组成的列表
'''
{'charles': 0, 'jason': 2, 'peggy': 1}
[('charles', 0), ('jason', 2), ('peggy', 1)]
[(0, 'charles'), (1, 'peggy'), (2, 'jason')]
[1, 2, 3, 4, 7, 9, 76]
[' ', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
[' ', 'd', 'e', 'h', 'l', 'o', 'r', 'w']
'''
print("\n")
seq_1 = ['charles','jason','peggy','thea']
seq_2 = ['one','two','three','four']
seq_3 = ['first','second']
print(sorted(zip(seq_1,seq_2)))
print(sorted(zip(seq_1,seq_2,seq_3))) #按照最短的序列决定
#enumerate和zip结合使用,迭代多个序列
for i, (a,b) in enumerate(zip(seq_1,seq_2)):
print("%d: %s, %s" % (i,a,b))
#对于已经要压缩好的数据,可以用*解压缩
zipped = zip(seq_1,seq_2)
name, seq = zip(*zipped)
print(name)
print(seq)
#*相当于zip(seq[0],seq[1],...,seq[len(seq)-1])
print(list(reversed(range(10))))
'''
[('charles', 'one'), ('jason', 'two'), ('peggy', 'three'), ('thea', 'four')]
[('charles', 'one', 'first'), ('jason', 'two', 'second')]
0: charles, one
1: jason, two
2: peggy, three
3: thea, four
('charles', 'jason', 'peggy', 'thea')
('one', 'two', 'three', 'four')
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
'''
empty_dict = {}
print(empty_dict)
#创建非空字典
d_1 = {'a':'hello world','b':[1,2,3,4]}
print(d_1)
#插入元素
d_1[7] = 'insert an integer'
print(d_1)
print(d_1['b'])#按照key取值
print('b' in d_1)#判断key是否在映射中
#q取出两个列表
print(d_1.keys())
print(d_1.values())
#删除刚才插入的元素
del d_1[7]
print(d_1)
#弹出一个key对应的东西,返回值是弹出的value
ret = d_1.pop('b')
print(ret)
print(d_1)
#刷新字典
d_1.update({'b':'fresh','a':'change that'})
print(d_1)
'''
{}
{'b': [1, 2, 3, 4], 'a': 'hello world'}
{'b': [1, 2, 3, 4], 'a': 'hello world', 7: 'insert an integer'}
[1, 2, 3, 4]
True
dict_keys(['b', 'a', 7])
dict_values([[1, 2, 3, 4], 'hello world', 'insert an integer'])
{'b': [1, 2, 3, 4], 'a': 'hello world'}
[1, 2, 3, 4]
{'a': 'hello world'}
{'b': 'fresh', 'a': 'change that'}
'''
mapping = dict(zip(range(5),reversed(range(5))))
print(mapping)
#{0: 4, 1: 3, 2: 2, 3: 1, 4: 0}
print("\n")
#get方法可以类似一个if-else循环
value = mapping.get(1,None)
print(value)
no_value = mapping.get(5,"nothing here")
print(no_value)
names = ['charles','apple','thea','jason']
by_latter = {}
for name in names:
letter = name[0]
if letter not in by_latter:
by_latter[letter] = [name]
else:
by_latter[letter].append(name)
print(by_latter)
#上面的这个模块也可以用setdefault代替
by_latter_new = {}
for name in names:
letter = name[0]
by_latter_new.setdefault(letter,[]).append(name)
print(by_latter_new)
#collections模块有一个叫做defaultdict的类,可以使得这个过程更加简单
from collections import defaultdict
by_letter_fresh = defaultdict(list)
for name in names:
by_letter_fresh[name[0]].append(name)
print(by_letter_fresh)
'''
3
nothing here
{'c': ['charles'], 't': ['thea'], 'j': ['jason'], 'a': ['apple']}
{'c': ['charles'], 't': ['thea'], 'j': ['jason'], 'a': ['apple']}
defaultdict(<class 'list'>, {'c': ['charles'], 't': ['thea'], 'j': ['jason'], 'a': ['apple']})
'''
print('\n')
print(hash('string'))
print(hash((1,2,(3,4))))
#print(hash((1,2,[3,4])))#这里会失败,因为列表是可变的
#要想使用列表做键,最简单的放哪个是就是转换成元组
d = {}
d[tuple([1,2,3])] = 5
print(d)
'''
-5979933153692547881
-2725224101759650258
{(1, 2, 3): 5}
'''
a_set = set([2,3,4,5,6,8,9,43])
print(a_set)
b_set = {2,3,5,7,89,5,3,1,3,5,6}
print(b_set)
print( a_set | b_set)#并集
print( a_set & b_set)#交集
print( a_set - b_set)#差集
print( a_set ^ b_set)#异或
c_set = {2,3,4}
print(c_set.issubset(a_set))#c是a的子集不是b的子集
print(c_set.issubset(b_set))
print(a_set == b_set)#内容相同就相等
a.add(x) | 元素x加入到集合a中 |
a.remove(x) | 元素x从集合a中删除 |
a.union(b) | 求合集 |
a.intersection(b) | 求并集 |
a.difference(b) | a-b差集 |
a.symmetric_difference(b) | 异或集合 |
a.issubset(b) | a是b的子集,为True |
a.issuperset(b) | b是a的子集,为True |
a.isdisjoint(b) | 没有公共元素,为True |
列表,集合以及字典的推导式:
names = ['thea','jason','apple','charles','heater','white']
print([x.upper() for x in names if len(x) > 4])
print("\n")
names = ['thea','jason','apple','charles','heater','white']
print([x.upper() for x in names if len(x) > 4])
unique_set = {len(x) for x in names}
print(unique_set)
unique_dict = {val:index for index,val in enumerate(names)}
print(unique_dict)
unique_dict_new = dict((val,idx) for idx,val in enumerate(names))
print(unique_dict_new)
'''
['JASON', 'APPLE', 'CHARLES', 'HEATER', 'WHITE']
{4, 5, 6, 7}
{'heater': 4, 'white': 5, 'apple': 2, 'thea': 0, 'jason': 1, 'charles': 3}
{'heater': 4, 'white': 5, 'apple': 2, 'thea': 0, 'jason': 1, 'charles': 3}
'''
print("\n")
#下面是一个列表的列表
name_name = [
['tom','jason','charles','lilei','shown','joe'],
['natasha','thea','ana','eva','peggy','heather']
]
#想要找到含有两个a的名字放到新的一个列表中
name = [name for names in name_name for name in names if name.count('a')>=2]
print(name)
#为了更清除这种嵌套,下面是一个例子
some_tuples = [(1,2,3),(4,5,6),(7,8,9)]
flattered = [x for tup in some_tuples for x in tup]
print(flattered)
'''
['natasha', 'ana']
[1, 2, 3, 4, 5, 6, 7, 8, 9]
'''
flat = []
for tup in some_tuples:
for x in tup:
flat.append(x)
print(flat)
Python语言精要---上的更多相关文章
- Python语言精要---下
函数: 可以返回多个值,其实函数是返回一个对象,就是元组,元组中的元素被拆分到各个结果变量中了 匿名函数: lambda函数,仅仅由单条语句组成,结果就是返回值 这种函数没有提供名称属性 闭包: cl ...
- Python语言在企业级应用上的十大谬误
英文原文:https://www.paypal-engineering.com/2014/12/10/10-myths-of-enterprise-python/ 翻译原文:http://www.os ...
- Python+selenium测试环境成功搭建,简单控制浏览器(firefox)接下来,继续学习其他浏览器上的测试环境搭建;学习Python语言,利用Python语言来写测试用例。加油!!!
Python+selenium测试环境成功搭建,简单控制浏览器(firefox)接下来,继续学习其他浏览器上的测试环境搭建:学习Python语言,利用Python语言来写测试用例.加油!!!
- 第 2 章 Python 语言入⻔
目录 2.1低而长的学习曲线 2.2Python的优势 2.3在你的计算机中安装Python 2.4如何运行Python程序 2.5文本编辑器 2.6寻求帮助 Python语言是一种流行的编程语言,在 ...
- 请不要重复犯我在学习Python和Linux系统上的错误
本人已经在运维行业工作了将近十年,我最早接触Linux是在大二的样子,那时候只追求易懂,所以就选择了Ubuntu作为学习.使用的对象,它简单.易用.好操作.界面绚丽,对于想接触Linux的新手来说是非 ...
- 关于《selenium2自动测试实战--基于Python语言》
关于本书的类型: 首先在我看来技术书分为两类,一类是“思想”,一类是“操作手册”. 对于思想类的书,一般作者有很多年经验积累,这类书需要细读与品位.高手读了会深有体会,豁然开朗.新手读了不止所云,甚至 ...
- [Python学习笔记1]Python语言基础 数学运算符 字符串 列表
这个系列是我在学习Python语言的过程中记录的笔记,主要是一些知识点汇总,而非学习教程,可供有一定编程基础者参考.文中偏见和不足难以避免,仅供参考,欢迎批评指正. 本系列笔记主要参考文献是官网文档: ...
- 如何系统地自学一门Python 语言(转)
转自:http://www.phpxs.com/post/4521 零基础情况下,学一门语言充实下自己,Python,简洁.优美.容易使用,是一个很好的选择.那么如何系统地自学Python呢? 有的人 ...
- 《Selenium2自动化测试实战--基于Python语言》 --即将面市
发展历程: <selenium_webdriver(python)第一版> 将本博客中的这个系列整理为pdf文档,免费. <selenium_webdriver(python)第 ...
随机推荐
- windbg定位WEB性能瓶颈案例一则
测试环境 服务器:II服务器 网站:门户网站 条件 并发: 2000 LoadRunner思考时间:1s 表现 CPU:100% 对应w3wp进程 WebService–>Current con ...
- 如何杀掉D状态的进程?[zt]【转】
转自:http://blog.csdn.net/chinalinuxzend/article/details/4288791 [-] 如何杀掉D状态的进程zt 相关博文 原贴:http://www ...
- Linux sar分析网卡流量
yum install sysstat sar -n { DEV | EDEV | NFS | NFSD | SOCK | ALL } sar 提供六种不同的语法选项来显示网络信息.-n选 ...
- DAO模型设计实现数据的 增,删,改,查方法
连接数据库方法,及反射获取数据,以前的方法相同,测试类 是在DAO模型下建立的 ------------------------------------------------------------ ...
- Dual Core CPU
Dual Core CPU Time Limit: 15000MS Memory Limit: 131072K Total Submissions: 20935 Accepted: 9054 Case ...
- Find The Multiple 分类: 搜索 POJ 2015-08-09 15:19 3人阅读 评论(0) 收藏
Find The Multiple Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 21851 Accepted: 8984 Sp ...
- 第十二届浙江省大学生程序设计大赛-Capture the Flag 分类: 比赛 2015-06-26 14:35 10人阅读 评论(0) 收藏
Capture the Flag Time Limit: 2 Seconds Memory Limit: 65536 KB Special Judge In computer security, Ca ...
- Python学习笔记-Day2-Python基础之字典操作
字典的常用操作包括但不限于以下操作: 字典的字典的索引,新增,删除,循环,长度等等 这里将对列表的内置操作方法进行总结归纳,重点是以示例的方式进行展示. 使用type获取创建对象的类 type(dic ...
- jar 文件
使用类库中的类: 1.当前应用程序所在目录中没有包名的类,直接用. 2.java库. import语句导入. 3.当前目录的子孙目录有报名的类,set classpath,之前有写. 4.扩展ext文 ...
- HDU(1853),最小权匹配,KM
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1853 Cyclic Tour Time Limit: 1000/1000 MS (Java/Other ...