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

本文深入探讨了Python中常用的基础类型,包括数值、字符串、列表、字典、元组、集合和其他核心类型。详细解释了数值运算、字符串操作、列表迭代、字典使用、元组特性以及集合应用。同时,提供了数学模块、随机模块、字符串格式化输出、列表的常用方法、文件操作、集合操作等高级功能的实例和说明。

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'}









                
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值