Detailed python data types (full)

1, the string
1.1, how to use Python string
a, single quotation marks ( ')
in single quotes string represents, for example:

str='this is string';
print str;

B, using the double quotes ( ")
String Usage double quotes string identical single quotes, for example:

str="this is string";
print str;

C, using a three-quotation marks ( '' ')
using the three quoted string representing a multi-line, single quotes may be used freely in the three quotes and double quotes, for example:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
str='''this is string
this is pythod string
this is string'''
print str;

2, Boolean type

bool=False;
print bool;
bool=True;
print bool;

3, integer

int=20;
print int;

4, floating point

float=2.3;
print float;

5, numbers
including integer, floating point.
5.1, delete digital object reference, for example:

a=1;
b=2;
c=3;
del a;
del b, c;
\#print a; #删除a变量后,再调用a变量会报错

5.2, numeric conversion

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
int(x [,base]) 将x转换为一个整数 
float(x ) 将x转换到一个浮点数 
complex(real [,imag]) 创建一个复数 
str(x) 将对象x转换为字符串 
repr(x) 将对象x转换为表达式字符串 
eval(str) 用来计算在字符串中的有效Python表达式,并返回一个对象 
tuple(s) 将序列s转换为一个元组 
list(s) 将序列s转换为一个列表 
chr(x) 将一个整数转换为一个字符 
unichr(x) 将一个整数转换为Unicode字符 
ord(x) 将一个字符转换为它的整数值 
hex(x) 将一个整数转换为一个十六进制字符串 
oct(x) 将一个整数转换为一个八进制字符串

5.3 Mathematical Functions

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
abs(x)    返回数字的绝对值,如abs(-10) 返回 10
ceil(x)    返回数字的上入整数,如math.ceil(4.1) 返回 5
cmp(x, y) 如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1
exp(x)    返回e的x次幂(ex),如math.exp(1) 返回2.718281828459045
fabs(x)    返回数字的绝对值,如math.fabs(-10) 返回10.0
floor(x) 返回数字的下舍整数,如math.floor(4.9)返回 4
log(x)    如math.log(math.e)返回1.0,math.log(100,10)返回2.0
log10(x) 返回以10为基数的x的对数,如math.log10(100)返回 2.0
max(x1, x2,...)    返回给定参数的最大值,参数可以为序列。
min(x1, x2,...)    返回给定参数的最小值,参数可以为序列。
modf(x)    返回x的整数部分与小数部分,两部分的数值符号与x相同,整数部分以浮点型表示。
pow(x, y) x**y 运算后的值。
round(x [,n]) 返回浮点数x的四舍五入值,如给出n值,则代表舍入到小数点后的位数。
sqrt(x)    返回数字x的平方根,数字可以为负数,返回类型为实数,如math.sqrt(4)返回 2+0j

6, a listing
6.1, the initialization list, for example:

list=['physics', 'chemistry', 1997, 2000];
nums=[1, 3, 5, 7, 8, 13, 20];

6.2, access the list of values, such as:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
'''nums[0]: 1'''
print "nums[0]:", nums[0]
'''nums[2:5]: [5, 7, 8] 从下标为2的元素切割到下标为5的元素,但不包含下标为5的元素'''
print "nums[2:5]:", nums[2:5]
'''nums[1:]: [3, 5, 7, 8, 13, 20] 从下标为1切割到最后一个元素'''
print "nums[1:]:", nums[1:]
'''nums[:-3]: [1, 3, 5, 7] 从最开始的元素一直切割到倒数第3个元素,但不包含倒数第三个元素'''
print "nums[:-3]:", nums[:-3]
'''nums[:]: [1, 3, 5, 7, 8, 13, 20] 返回所有元素'''
print "nums[:]:", nums[:]

6.3, update the list, such as:

nums[0]="ljq";
print nums[0];

6.4, delete list elements

del nums[0];
'''nums[:]: [3, 5, 7, 8, 13, 20]'''
print "nums[:]:", nums[:];

6.5, operator list script
list of + and similar string operators. + Sign for the combined list, numbers for repeating the list, for example:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
print len([1, 2, 3]); #3
print [1, 2, 3] + [4, 5, 6]; #[1, 2, 3, 4, 5, 6]
print ['Hi!'] * 4; #['Hi!', 'Hi!', 'Hi!', 'Hi!']
print 3 in [1, 2, 3] #True
for x in [1, 2, 3]: print x, #1 2 3

6.6 interception list

L=['spam', 'Spam', 'SPAM!'];
print L[2]; #'SPAM!'
print L[-2]; #'Spam'
print L[1:]; #['Spam', 'SPAM!']

6.7, the list of functions & methods

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
list.append(obj) 在列表末尾添加新的对象
list.count(obj) 统计某个元素在列表中出现的次数
list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
list.index(obj) 从列表中找出某个值第一个匹配项的索引位置,索引从0开始
list.insert(index, obj) 将对象插入列表
list.pop(obj=list[-1]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
list.remove(obj) 移除列表中某个值的第一个匹配项
list.reverse() 反向列表中元素,倒转
list.sort([func]) 对原列表进行排序

7, the tuple (tuple)

Similar tuple Python list, except that the elements of the tuple can not be modified; tuple using parentheses (), a list of square brackets []; tuple created is very simple, only you need to add elements in parentheses, using comma (,) can be separated, for example:

tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";

Empty tuples, for example: tup = ();

Tuple only one element, the element needs to be added after the comma, for example: tup1 = (50,);

Tuple string Similarly, the subscript index starts from 0, may be taken, and other combinations.

7.1, visit tuple

tup1 = ('physics', 'chemistry', 1997, 2000);
#tup1[0]: physics
print "tup1[0]: ", tup1[0]
#tup1[1:5]: ('chemistry', 1997)
print "tup1[1:5]: ", tup1[1:3]

7.2, modify tuple
element values tuple can not be modified, but we may be connected to a combination of tuples, for example:

tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');

# The following modifications tuple element operation is illegal.
# Tup1 [0] = 100;

# Create a new tuple

tup3 = tup1 + tup2;
print tup3; #(12, 34.56, 'abc', 'xyz')

7.3, delete tuple
element values in the tuple is not allowed to delete, you can use the del statement to delete an entire tuple, for example:

tup = ('physics', 'chemistry', 1997, 2000);
print tup;
del tup;

7.4, operator tuple
string as + and * can be used for operation between the number of tuples. This means that they can be combined and after replication operation will generate a new tuple.

img

7.5, & taken index tuple

L = ('spam', 'Spam', 'SPAM!');
print L[2]; #'SPAM!'
print L[-2]; #'Spam'
print L[1:]; #['Spam', 'SPAM!']

7.6, built-in functions tuple

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
cmp(tuple1, tuple2) 比较两个元组元素。
len(tuple) 计算元组元素个数。
max(tuple) 返回元组中元素最大值。
min(tuple) 返回元组中元素最小值。
tuple(seq) 将列表转换为元组。

8, Dictionary

8.1 Introduction dictionary
Dictionary (dictionary) python is outside the list of the most flexible structure of built-in data types other. Is an ordered list of target binding, dictionaries are unordered collections of objects. The difference between the two is that: among the elements of the dictionary is accessed by a key, rather than by shifting access.

The dictionary by the key and the corresponding values. Dictionary also referred associative array or hash table. The basic syntax is as follows:

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'};

So also create a dictionary:

dict1 = { 'abc': 456 };
dict2 = { 'abc': 123, 98.6: 37 };

Each key value must be separated by a colon (:), each pair separated by commas, the whole in curly braces ({}). Key must be unique, but the value is not necessary; type of data may take any value, but must be immutable, such as a string, or the number of tuples.

8.2, access to the dictionary values

#!/usr/bin/python
dict = {'name': 'Zara', 'age': 7, 'class': 'First'};
print "dict['name']: ", dict['name'];
print "dict['age']: ", dict['age'];

8.3, modify the dictionary
to add new content to the dictionary method is to add a new key / value pairs, modify or delete existing key / value pairs in the following examples:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
#!/usr/bin/python
dict = {'name': 'Zara', 'age': 7, 'class': 'First'};
dict["age"]=27; #修改已有键的值
dict["school"]="wutong"; #增加新的键/值对
print "dict['age']: ", dict['age'];
print "dict['school']: ", dict['school'];

8.4, deleting dictionary
del dict [ 'name']; # delete key is 'name' entry
dict.clear (); # Clear all dictionary entries
del dict; # remove dictionaries
example:

#!/usr/bin/python
dict = {'name': 'Zara', 'age': 7, 'class': 'First'};
del dict['name'];
#dict {'age': 7, 'class': 'First'}
print "dict", dict;

Note: The dictionary does not exist, del raises an exception

8.5, built-in functions & dictionary method

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
cmp(dict1, dict2) 比较两个字典元素。
len(dict) 计算字典元素个数,即键的总数。
str(dict) 输出字典可打印的字符串表示。
type(variable) 返回输入的变量类型,如果变量是字典就返回字典类型。
radiansdict.clear() 删除字典内所有元素
radiansdict.copy() 返回一个字典的浅复制
radiansdict.fromkeys() 创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
radiansdict.get(key, default=None) 返回指定键的值,如果值不在字典中返回default值
radiansdict.has_key(key) 如果键在字典dict里返回true,否则返回false
radiansdict.items() 以列表返回可遍历的(键, 值) 元组数组
radiansdict.keys() 以列表返回一个字典所有的键
radiansdict.setdefault(key, default=None) 和get()类似, 但如果键不已经存在于字典中,将会添加键并将值设为default
radiansdict.update(dict2) 把字典dict2的键/值对更新到dict里
radiansdict.values() 以列表返回字典中的所有值

9, the date and time

9.1, obtain the current time, for example:

import time, datetime;

localtime = time.localtime(time.time())
\#Local current time : time.struct_time(tm_year=2014, tm_mon=3, tm_mday=21, tm_hour=15, tm_min=13, tm_sec=56, tm_wday=4, tm_yday=80, tm_isdst=0)
print "Local current time :", localtime

Description: time.struct_time (tm_year = 2014, tm_mon = 3, tm_mday = 21, tm_hour = 15, tm_min = 13, tm_sec = 56, tm_wday = 4, tm_yday = 80, tm_isdst = 0) belonging struct_time tuple, struct_time tuple It has the following attributes:

img

9.2, obtaining formatting time
can be selected according to the needs of a variety of formats, but the easiest time to get the function-readable pattern is the asctime ():
2.1, into a string date

首选:print time.strftime('%Y-%m-%d %H:%M:%S');
其次:print datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
最后:print str(datetime.datetime.now())[:19]

2.2, string into the date

expire_time = "2013-05-21 09:50:35"
d = datetime.datetime.strptime(expire_time,"%Y-%m-%d %H:%M:%S")
print d;

9.3, the difference between the date of acquisition

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
oneday = datetime.timedelta(days=1)
#今天,2014-03-21
today = datetime.date.today()
#昨天,2014-03-20
yesterday = datetime.date.today() - oneday
#明天,2014-03-22
tomorrow = datetime.date.today() + oneday
#获取今天零点的时间,2014-03-21 00:00:00
today_zero_time = datetime.datetime.strftime(today, '%Y-%m-%d %H:%M:%S')

#0:00:00.001000 
print datetime.timedelta(milliseconds=1), #1毫秒
#0:00:01 
print datetime.timedelta(seconds=1), #1秒
#0:01:00 
print datetime.timedelta(minutes=1), #1分钟
#1:00:00 
print datetime.timedelta(hours=1), #1小时
#1 day, 0:00:00 
print datetime.timedelta(days=1), #1天
#7 days, 0:00:00
print datetime.timedelta(weeks=1)

9.4, to obtain the time difference

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
#1 day, 0:00:00
oneday = datetime.timedelta(days=1)
#今天,2014-03-21 16:07:23.943000
today_time = datetime.datetime.now()
#昨天,2014-03-20 16:07:23.943000
yesterday_time = datetime.datetime.now() - oneday
#明天,2014-03-22 16:07:23.943000
tomorrow_time = datetime.datetime.now() + oneday
注意时间是浮点数,带毫秒。

那么要获取当前时间,需要格式化一下:
print datetime.datetime.strftime(today_time, '%Y-%m-%d %H:%M:%S')
print datetime.datetime.strftime(yesterday_time, '%Y-%m-%d %H:%M:%S')
print datetime.datetime.strftime(tomorrow_time, '%Y-%m-%d %H:%M:%S')

9.5, access to the last day of last month

last_month_last_day = datetime.date(datetime.date.today().year,datetime.date.today().month,1)-datetime.timedelta(1)

9.6 seconds formatted date string, floating-point return type:

expire_time = "2013-05-21 09:50:35"
d = datetime.datetime.strptime(expire_time,"%Y-%m-%d %H:%M:%S")
time_sec_float = time.mktime(d.timetuple())
print time_sec_float

9.7, the date format for the number of seconds, return the floating-point type:

d = datetime.date.today()
time_sec_float = time.mktime(d.timetuple())
print time_sec_float

9.8, the number of seconds to String

time_sec = time.time()
print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time_sec))

Guess you like

Origin blog.51cto.com/14246112/2429925