python学习笔记(一)------ core types

1.Python常用build-in类型:

Object type  Exampleliterals/creation

Numbers  123

Strings  'spam',"guido's", b'a\x01c'

Lists  [1, [2, 'three'], 4]

Dictionaries  {'food':'spam', 'taste': 'yum'}

Tuples (1, 'spam', 4, 'U')Files myfile =open('eggs', 'r')

Sets  set('abc'),{'a', 'b', 'c'}

Other core types  Booleans,types, None


2.Numbers

>>> 1.5 * 4 # Floating-point multiplication
6.0
>>> 2 ** 100 # 2 to the power 100
1267650600228229401496703205376
>>> 3.1415 * 2 # repr: as code
6.2830000000000004
>>> print(3.1415 * 2) # str: user-friendly
6.283
Math module
>>> import math
>>> math.pi
3.1415926535897931
>>> math.sqrt(85)
9.2195444572928871
random module
>>> import random
>>> random.random()
0.59268735266273953
>>> random.choice([1,2,3,4,5])
5
>>> random.choice([1,2,3,4,5])
3

3.Strings

>>> s="abcdefghijklmnopqrstuvwxyz"  
>>> s[1::2]	#步长为2
'bdfhjlnprtvxz' 
>>> s[1:10:2]
'bdfhj'		
>>> s[1:4]	#包前不包后,实际上输出的是s[1]-s[3]
'bcd'	
>>> s[5:]	
'fghijklmnopqrstuvwxyz'
>>> s[:5]
'abcde'
>>> s*2
'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'
>>> s[-1]	#倒数第一
'z'
>>> s="""aaaaaaa	#多行,换行符会被表示出来
efase
eafef"
eqrtq'
wersaf"""
>>> s
'aaaaaaa\nefase\neafef"\neqrtq\'\nwersaf'
>>> a='safe\	#多行,无换行符
safae'
>>> a
'safesafae'
格式化输出
>>> '%s, eggs, and %s' % ('spam', 'SPAM!') # Formatting expression (all)
'spam, eggs, and SPAM!'
>>> '{0}, eggs, and {1}'.format('spam', 'SPAM!') # Formatting method (2.6, 3.0)
'spam, eggs, and SPAM!'
常用方法:
>>> S.find('pa') # Find the offset of a substring
1
>>> S			#String是不可变类
'Spam'
>>> S.replace('pa', 'XYZ') # Replace occurrences of a substring with another
'SXYZm'
>>> S
'Spam'
>>> line = 'aaa,bbb,ccccc,dd'
>>> line.split(',') # Split on a delimiter into a list of substrings
['aaa', 'bbb', 'ccccc', 'dd']
>>> S = 'spam'
>>> S.upper() # Upper- and lowercase conversions
'SPAM'
>>> S.isalpha() # Content tests: isalpha, isdigit, etc.
True
>>> line = 'aaa,bbb,ccccc,dd\n'
>>> line = line.rstrip() # Remove whitespace characters on the right side
>>> line
'aaa,bbb,ccccc,dd'
>>> S = 'A\nB\tC' # \n is end-of-line, \t is tab
>>> len(S) # Each stands for just one character
5
>>> ord('\n') # \n is a byte with the binary value 10 in ASCII
10
>>> S = 'A\0B\0C' # \0, a binary zero byte, does not terminate string
>>> len(S)
5

4.Lists

List的迭代写法
>>> M=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> col2 = [row[1] for row in M]
>>> col2
[2, 5, 8]
>>> [row[1] for row in M if row[1] % 2 == 0]
[2, 8]
>>> [row[1] for row in M if not row[1] % 2 == 0]
[5]
>>> L=[sum(row) for row in M]  #得到一个list
>>> L
[6, 15, 24]
>>> D={sum(row) for row in M}   #得到一个set
>>> D
set([24, 6, 15])
>>> {i : sum(M[i]) for i in range(3)}  #得到一个dictionary
{0: 6, 1: 15, 2: 24}
>>> list(map(sum, M))    #使用map build-in
[6, 15, 24]

5.Dictionaries

>>> rec = {'name': {'first': 'Bob', 'last': 'Smith'},	#Dictionary也是不可变类
'job': ['dev', 'mgr'],
'age': 40.5}
>>> rec = 0	#清理
>>> D[6]	#key不存在会报错
Traceback (most recent call last):
  File "<pyshell#53>", line 1, in <module>
    D[6]
KeyError: 6
避免报错的方法:
>>> value = D.get('x', 0) # Index but with a default
>>> value
0
>>> value = D['x'] if 'x' in D else 0 # if/else expression form
>>> value
0


6.Tuples

>>> a=(0,1,2,3,4,5)
>>> a.index(4)
4

7.Files

写入文件:

>>> f = open('data.txt', 'w') # Make a new file in output mode
>>> f.write('Hello\n') # Write strings of bytes to it
6
>>> f.write('world\n') # Returns number of bytes written in Python 3.0
6
>>> f.close() # Close to flush output buffers to disk

读入文件:

>>> f = open('data.txt') # 'r' is the default processing mode
>>> text = f.read() # Read entire file into a string
>>> text
'Hello\nworld\n'


8.set

>>> X = set('spam') # Make a set out of a sequence in 2.6 and 3.0
>>> Y = {'h', 'a', 'm'} # Make a set with new 3.0 set literals
>>> X, Y
({'a', 'p', 's', 'm'}, {'a', 'h', 'm'})
>>> X & Y # Intersection
{'a', 'm'}
>>> X | Y # Union
{'a', 'p', 's', 'h', 'm'}
>>> X – Y # Difference
{'p', 's'}








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Python学习笔记》是由皮大庆编写的一本关于Python语言学习的教材。在这本书中,作者详细介绍了Python语言的基础知识、语法规则以及常用的编程技巧。 首先,作者简要介绍了Python语言的特点和优势。他提到,Python是一种易于学习和使用的编程语言,受到了广大程序员的喜爱。Python具有简洁、清晰的语法结构,使得代码可读性极高,同时也提供了丰富的库和模块,能够快速实现各种功能。 接着,作者详细讲解了Python的基本语法。他从变量、数据类型、运算符等基础知识开始,逐步介绍了条件语句、循环控制、函数、模块等高级概念。同时,作者通过大量的示例代码和实践案例,帮助读者加深对Python编程的理解和应用。 在书中,作者还特别强调了编写规范和良好的编程习惯。他从命名规范、注释风格、代码缩进等方面指导读者如何写出清晰、可读性强的Python代码。作者认为,良好的编程习惯对于提高代码质量和提高工作效率非常重要。 此外,作者还介绍了Python的常用库和模块。他提到了一些常用的库,如Numpy、Pandas、Matplotlib等。这些库在数据处理、科学计算、可视化等领域有广泛的应用,帮助读者更好地解决实际问题。 总的来说,《Python学习笔记》是一本非常实用和全面的Python学习教材。通过学习这本书,读者可以系统地学习和掌握Python编程的基础知识和高级应用技巧,为以后的编程学习和工作打下坚实的基础。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值