python基础学习之数据类型和基本操作函数
2018-04-16 10:40:07         来源：键盘会跳舞

python基础学习之数据类型和基本操作函数

2018/4/14
python note

apple_price = 10
apple_weight = 2
apple_cost = apple_price * apple_weight
print(apple_cost)

grape_price = 15
grape_weight = 1.5
grape_cost = grape_price * grape_weight
print(grape_cost)

total_cost = apple_cost + grape_cost
"apple_cost:{};grape_cost:{};total_cost:{}".format(apple_cost,grape_cost,total_cost)

#语法糖
a = 10
b = 20
a,b = b,a

#格式化输出
print("a is {},b is {}".format(a,b))

#按位取整
round(100/3,3)

P147

1、不要使用单字符
2、变量名能清晰表达标量的意义
3、合理使用字母中加的下划线

-----------------------------

1、字符串 str
2、数字 int float complex
3、列表 list
4、元组 tuple
5、字典 dict

num += 10
Num -= 10
Num *= 10
Num /= 10

>>> import math
#乘方
>>> math.pow(10,3)
1000.0
>>> 3 ** 10
59049
>>> 10 ** 3
1000

#向下取整
math.floor(2.1)
2

#向上取整
>>> math.ceil(2.1)
3

#度的转换
3.141592653589793

>>>> math.sin(math.pi/2)
1.0

>>>>min(12.3,18,243,4)
4
>>> max(12.3,18,243,4)
243

#求和
>>> sum([12.3,18,243,4])
277.3

#求商和余数
>>> pmod(10,3)
(3, 1)

bool类型
True，False
True == 1
False == 0

Bool类型运算：与运算、或运算、非运算

True and True
True
>>> True and False
False

>>> True or False
True

>>> not True
False

#字符串可以使用单、双引号，通过单、双引号的恰当使用，可以避免不必要的字符转译，（escape），也就是说，可以避免使用（\ 转义字符）
In [1]: line = "hello world"
In [2]: print(line)
hello world
In [3]: line = "hello world\""
In [4]: print(line)
hello world"
In [5]: line = 'hello \'world'
In [6]: print(line)
hello 'world

#字符串的加法操作
>>> line_1 = "nihao, "
>>> line_2 ="xiaojiejie"
>>> print(line_1+line_2)
nihao, xiaojiejie

#字符串的乘法操作
>>> line = 'nihao'
>>> print(line*3)
nihaonihaonihao

#字符串的长度
>>> line = 'ni hao'
>>> len(line)
6

>>> line = 'ni hao'
>>> id(line)
4498582696
>>> line = 'buhao'
>>> id(line)
4498582752

>>> line = 'huan yin da jia'

#取前10个字符
>>> line[:10]
'huan yin d'
>>> line[:10:1]
'huan yin d'
>>> line[:10:2]
'ha i '
>>> line_len = len(line)
>>> line[:line_len:2]
'ha i aja'

#取后10个字符
>>> line[-10:]
'yin da jia'

#翻转字符
>>> line[::-1]

#取单字符
line[1]
'u'

///////字符串相关函数/////////
line.capitalize()   line.isidentifier()  line.rindex()
line.casefold()     line.islower()       line.rjust()
line.center()       line.isnumeric()     line.rpartition()
line.count()        line.isprintable()   line.rsplit()
line.encode()       line.isspace()       line.rstrip()
line.endswith()     line.istitle()       line.split()
line.expandtabs()   line.isupper()       line.splitlines()
line.find()         line.join()          line.startswith()
line.format()       line.ljust()         line.strip()
line.format_map()   line.lower( )        line.swapcase()
line.index()        line.lstrip( )       line.title()
line.isalnum()      line.maketrans()     line.translate()
line.isalpha()      line.partition( )    line.upper()
line.isdecimal()    line.replace( )      line.zfill()
line.isdigit()

#第一个字符大写，其他的字符全部变成小写
>>> line.capitalize()
'Huan yin da jia'

#居中
>>> line.center(20,"%")
'%%huan yin da jia%%%'

#计数
>>> line.count('a')
3

#字符串的首位判断
>>> line.startswith('a')
False
>>> line.endswith('a')
True
>>> line.endswith('jia')
True

# find:存在返回第一个字符的下标，不存在返回-1
>>> line.find('h')
0
>>> line.find('a')
2

#index:存在返回第一个字符的下标，不存在会报错
>>> line.index('z')
Traceback (most recent call last):
File "", line 1, in
>>> line.index('a')
2

#大小写转换
>>> line.upper()
>>> line.lower()

#判断是否是大写/小写
>>> line.isupper()
False
>>> line.islower()
False

#判断字符串是否是title：首字母大写，其他字符都是小写的为title
>>> line_1 = line.capitalize()
>>> line_1.istitle()
True

>>> line  = '   dhiaf \ hdha knadfj'
>>> line.strip()
>>> line.lstrip()

#空列表
>>> varibals = []
>>> varibals = list()

varibals = [1,2,3,4,'ni hao',"hello world",[],[11,22,33]]
>>> print(varibals)
[1, 2, 3, 4, 'ni hao', 'hello world', [], [11, 22, 33]]

#向空列表中插入数据
>>> varlist = []
>>> varlist.append(1)
>>> varlist
[1]
>>> varlist.append("hello")
>>> varlist.append('world')
>>> varlist1 = [2,'girl is','beautiful']
>>> varlist.append(varlist1)
>>> print(varlist)
[1, 'hello', 'world', [2, 'girl is', 'beautiful']]

#修改列表中某个位置元素的值
>>> varlist[1] = 10
>>> print(varlist)
[1, 10, 'world', [2, 'girl is', 'beautiful']]

#python是一种动态类型的语言，一个变量是什么类型，要看程序在运行过程中变量所表示的值是什么

>>> var = 10
>>> type(var)

>>> var = 'hello'
>>> type(var)

>>> var = [1,3]
>>> type(var)

#切片 : 与字符串类型的切片操作基本一致
>>> varlist
[1, 10, 'world', [2, 'girl is', 'beautiful']]
>>> varlist[-2:]
['world', [2, 'girl is', 'beautiful']]
>>> varlist[2:]
['world', [2, 'girl is', 'beautiful']]
>>> varlist[:2]
[1, 10]
>>> varlist[::2]
[1, 'world']

>>> varlist
[1, 10, 'world', [2, 'girl is', 'beautiful']]
>>> varlist + [111,222]
[1, 10, 'world', [2, 'girl is', 'beautiful'], 111, 222]
>>> varlist*2
[1, 10, 'world', [2, 'girl is', 'beautiful'], 1, 10, 'world', [2, 'girl is', 'beautiful']]
>>>

varlist.append()   varlist.count( )   varlist.insert( )  varlist.reverse()
varlist.clear()    varlist.extend( )  varlist.pop( )     varlist.sort()
varlist.copy()     varlist.index(  )  varlist.remove()

help> list

|
|  __sizeof__(...)
|      L.__sizeof__() -- size of L in memory, in bytes
|
|  append(...)
|      L.append(object) -> None -- append object to end
|
|  clear(...)
|      L.clear() -> None -- remove all items from L
|
|  copy(...)
|      L.copy() -> list -- a shallow copy of L
|
|  count(...)
|      L.count(value) -> integer -- return number of occurrences of value
|
|  extend(...)
|      L.extend(iterable) -> None -- extend list by appending elements from the iterable
|
|  index(...)
|      L.index(value, [start, [stop]]) -> integer -- return first index of value.
|      Raises ValueError if the value is not present.
|
|  insert(...)
|      L.insert(index, object) -- insert object before index
|
|  pop(...)
|      L.pop([index]) -> item -- remove and return item at index (default last).
|      Raises IndexError if list is empty or index is out of range.
|
|  remove(...)
|      L.remove(value) -> None -- remove first occurrence of value.
|      Raises ValueError if the value is not present.
|
|  reverse(...)
|      L.reverse() -- reverse *IN PLACE*
|
|  sort(...)
|      L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
|
|  ----------------------------------------------------------------------
|  Data and other attributes defined here:
|
|  __hash__ = None

----===============

Tuple: 元组 :不可变列表

Var = tuple()
Var = ()

>>> var = (1,2,'hhh',[22,33])
>>> var
(1, 2, 'hhh', [22, 33])

var.count()  var.index()

==================
ditc : 字典类型

Var = {}
Var = dict()
type(var)

>>> var = {}
>>> type(var)

>>> var = {
... '中':100,
... '左':600
... }
>>> var
{'中': 100, '左': 600}
>>> var['中']
100

>>> word = ['中','左']
>>> location = [100,600]
>>> location[word.index('中')]
100

#拉索函数[zip（）]
>>> zip(word,location)

>>> list(zip(word,location))
[('中', 100), ('左', 600)]

157_20180414