python实操(5):python数据类型及常用操作,数字、字符串、元组、列表、字典、集合

#!/usr/bin/python
# encoding:utf-8
# Filename : pythonDataType.py
# author by :morespeech
# python2.7
# platform:visual studio code, windows
# topic: practice every day
# detial: describe Python data type

# !/usr/bin/env python
# -*- coding:utf-8 -*-

import math


class cPythonDataType:
    def number(self):
        print ("add:   x+y=", 6 + 2)
        print ("plus:  x-y=", 6 - 2)
        print ("mult:  x*y=", 6 * 2)
        print ("divide:x/y=", 6 / 2)
        print ("mode:  x%y=", 6 % 2)
        print ("power: x**y=", 6 ** 2)
        print ("sqrt: sqrt(x)=", math.sqrt(6))

    def string(self):
        string = "morespeech"
        print string           # index [0, len]
        print (string[0:])     # index [0, len)
        print (string[2:])     # index [2,len)
        print (string[2:6])    # index [2, 6)
        print string * 2       # double print
        print string + string  # double print

# 列表:使用‘[]’,一种有序的集合,元素可变,可以随时添加和删除其中元素
    def list(self):
        L = list("morespeech")  # create list
        print '(0):', L
        nElement = len(L)
        print '(1):', nElement  # number of elements in list
        print '(2):', L[0]      # access first element
        print '(3):', L[-1]     # access last element
        L.insert(0, ' world')   # insert element in special position
        print '(4):', L
        L.append(' hello')      # append element
        print '(5):', L
        L.remove(' world')      # remove first matching element
        print '(6):', L
        L.extend(L)             # extend list; add a new list at the tail
        print '(7):', L
        L.reverse()             # reverse elements
        print '(8):', L
        L.sort()                # sort list
        print '(9):', L
        cnt = L.count('e')      # cout the number of occurrences of the element
        print '(10):', cnt
        index = L.index('e')    # get the first matching position of element
        print '(11):', index

# 元组:使用‘()’,与列表类似,但元素不能修改
    def tuple(self):
        tup1 = ('more ', 'speech')
        tup2 = (2, 0, 1, 7)
        print '(0):', tup1[0]        # access first element
        print '(1):', tup1+tup2      # join the tuple
        maxval = max(tup2)           # get the max value in tuple
        print '(2):', maxval
        retval = cmp(tup1, tup1)     # compare tup1 with tup2: retval=0, same; retval=1,diff
        print '(3):', retval
        nElem = len(tup1)            # number of elements in tuple
        print '(4):', nElem
        new_tup = tuple([1, 2])      # list -> tuple
        print '(5):', new_tup
        print '(6):',
        for elem in tup1:            # traversal tuple
            print elem,

# 字典:使用‘{}’, 是一种无序的对象组合,字典中的元素通过键来获取,j键和值一一对应
    def dict(self):
        dict1 = {'more': 1, 'speech': 2}
        dict2 = {'2': 2}
        print '(0):', dict1['speech']        # access element
        dict1['hello'] = 4                   # add a new element
        print '(1):', dict1
        del dict1['hello']                   # delete element
        print '(2):', dict1
        retval = cmp(dict1, dict2)           # compare dict1 with dict2: retval=0, same;1, dict1>dict2;-1, dict1<dict2
        print '(3):', retval
        nElem = len(dict1)                   # number of elements in dict
        print '(4):', nElem
        keys = dict1.keys()                  # get all the dict keys
        print '(5):', keys
        values = dict1.values()              # get all the dict values
        print '(6):', values
        retval = 'more' in dict1             # check the key exists: exist, retval = true; or, retval = false
        print '(7):', retval
        value = dict1.get('more', None)      # get the value correspond to key 'more'
        print '(8):', value
        dict1.update(dict2)                  # add dict2 to dict1
        print '(9):', dict1
        dict1.clear()                        # clear the dict
        print '(10):', dict1
        del dict1                            # delete dict
        # print dict1                        # error, dict1 does not exist

# 集合: 建立无序的,'不重合'的元素
    def set(self):
        S1 = set(['more', 'speech', 1, 2, 3])  # create set using list
        S2 = set(['more', 'speech', 'hello'])
        print '(0):', S1
        S1.add('hello')                        # add a new element
        print '(1):', S1
        S1.remove('hello')                     # remove a element
        print '(2):', S1
        S = S1 & S2                            # intersection: S1 ∩ S2, get the common elements between S1 and S2
        print '(3):', S
        S = S1 | S2                            # union: S1 ∪ S2
        print '(4):', S


if __name__ == "__main__":
    # cPythonDataType().number()
    # cPythonDataType().string()
    # cPythonDataType().list()
    # cPythonDataType().tuple()
    # cPythonDataType().dict()
    cPythonDataType().set()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值