Getting Started with Python Python's basic data type and its methods

Getting Started with Python Python's basic data types

1, integer: int

For calculating, for comparison (right-hand side before the implementation of the content at the time of assignment)

Integer plus 1.1

a = 10
b = 20
print(a + b)
结果:
30

1.2 Save integer

a = 10
b = 20
print(b - a)
结果
10

1.3 integer multiplication

a = 10
b = 20
print(a * b)
结果:
200

1.4 In addition to integer

a = 10
b = 20
print(b / a)
结果:
2.0
# 注意点:当我们使用Python3的时候我们除法获取到时浮点数,也就是小数,但是使用Python2的时候使用除法获取的就是整数

Integers divisible 1.5

a = 10
b = 20
print(b // a)
结果:
2

1.6 of integers modulo

a = 5
b = 2
print(a % b)
结果:
1

1.7 integer power (power)

a = 5
b = 2
print(a ** b)
结果:
25

(Time division returned to python3 decimal (floating point), Python2 time division returns an integer (rounded down))

On 32-bit machines int ranges: -2 31 to 2 31 - 1 ~ -2147483648 2147483647 i.e.

Int 64-bit machine in the range: -2 63 to 2 63-1 ~ 9223372036854775807 i.e. -9223372036854775808

Integer in Python2 and Python3 the difference:

Python3: All integer

Python2: int, long long

1.8 10 rpm binary decimal conversion

1.8.1 transfected decimal binary: bin () function

Methods: In addition to 2 remainder, from the write-up

print(bin(30))

1.8.2 decimal binary rotation: int ( "11011101", 2) Function

Method: the position of the current number is multiplied by 2 minus 1 th bits, and added to

print(int("111110",2))

2, Boolean values: bool

true - true false - false :( for judgment)

print(3 > 2)         # 输出借结果为True
print(3 < 2)        # 输出结果为False

3, the string: str

For storing some data storing small amounts of data. In Python long as it is enclosed in quotation marks is the string, each letter or character string is called an element (string concatenation: String String String double +: string * Digital)

a = """absc"""
print(a)

3.1 adder string

#字符串的拼接
s1 = 'a' 
s2 = 'bc'
print(s1 + s2)

3.2 string multiplication (multiplication rule: only strings and numbers multiplied)

str*int name = '小强'
print(name*8)

The string can not be subtraction and division operations

3.3 index (subscript):

<1> row from left to right (forward index starting from 0)

<2> row from right to left (reverse index starting at -1)

a = "hello_wiu_srr,_taa_ba_hello"
print(a[5])
print(a[6])
print(a[11])
print(a[-2])
print(a[-1])

The index when the index can not exceed the maximum

3.4 sections:

[Starting position (comprising): end position (not included)]: care regardless tail

[Start position:]: starting from the default to the last

[:]: The default from the beginning to the end

Slice when you can exceed the index value

a = "hello_wiu_srr,_taa_ba_hello"
print(a[21:100])
print(a[21:])    # [21(起始位置):(默认到最后)]
print(a[:])      # [(默认从最开始):(默认到最后)]

3.5 Step:

Mai's decision to find direction when the step size, and to find the pace

Slice the time step size defaults to 1

A positive number for the forward index (left to right), reverse negative index (right to left)

In the end position: the starting position of the next character + element obtained in steps

[:: --1]: inverted output string

a = "hello_wiu_srr,_taa_ba_hello"
print(a[1:8:2]) 
print(a[1:8:4]) 

print(a[-12:-3:2])  
print(a[10:-5:1])
print(a[-5:-10:-1])

Strings are immutable data type, the string is ordered

3.6 string methods:

<1> upper (): all caps

name = "maex"
a = name.upper()  # 全部大写
print(a)
print(name)

<2> lower (): all lowercase

name = "MAEX"
a = name.lower()   # 全部小写
print(name)
print(a)

<3> startswith (): What to begin with

name = "maex"
print(name.startswith('e',2,3))  # 以什么开头 -- 返回的是布尔值

<4> endswith (): to what end

name = "maex"
print(name.endswith('l',0,2))    # 以什么结尾 -- 返回的是布尔值

<5> count (): Statistics, count

name = "maexwauisrtaaibbIa"
print(name.count("i"))      # 统计,计数

<6> strip (): off (off the head and tail ends of the space, newline \ n-, tab \ T); removing the head and tail ends specified content

pwd = " wslexsdsb   "
a = pwd.strip()   # 脱 默认脱(脱头尾两端的空格,换行符\n,制表符\t)
print(a)

pwd = "alxasdsbala"
a = pwd.strip("al")  # 去除头尾两端指定的内容
print(a)

<7> split (): split (space by default, newline \ n-, tab \ T); you can also split the specified element. You can specify the number of split

name = "allwex_wusu_sdi_r"
a = name.split("_")        # 分割(默认空格,换行符\n,制表符\t)
print(a)                  

print(name.split("_",2))   # 可以指定分割的次数

<8> replace ():. Alternatively the Replace ( "content to be replaced," "is replaced with the content," Replace times)

name = "alex,wusir,ta,i,b,a,i"
a = name.replace(",",".")               # 全部替换
print(a)

a = name.replace(",",".",4)              # 可以指定替换的次数
print(a)

3.7 string formatting:

format (): the position is filled in accordance with the order; filled by index; new filling by name

name = "{}今年:{}".format("宝元",18)    # 按照位置顺序进行填充
print(name)

name = "{1}今年:{0}".format("宝元",18)    # 按照索引进行填充
print(name)

name = "{name}今年:{age}".format(name="宝元",age=18)    # 按照名字进行填充
print(name)

3.8 is a series judge returns a Boolean value

(1) isdigit (): the contents of the string is determined not all numbers (digits)

msg = "alex"
print(msg.isdigit())      # 判断字符串中的内容是不是全都是数字(阿拉伯数字)

(2) isdecimal (): a decimal number judgment is not

msg = "alex"
print(msg.isdecimal())    # 判断是不是十进制数

(3) isalnum (): judgment is not numbers, letters, Chinese

msg = "alex"
print(msg.isalnum())      # 判断是不是数字,字母,中文

(4) Isalpha (): judgment is not letters, Chinese

msg = "alex"
print(msg.isalpha())      # 判断是不是字母,中文

3.9 str data type methods - added:

<1> string name .capitalize (): capitalize the first letter

a = "alex Wusir"
print(a.capitalize())   # 首字母大写

<2> string name .title (): capitalize the first letter of each word

a = "alex Wusir"
print(a.title())        # 每个单词首字母大写

<3> string name .swapcase (): Case swap

a = "alex Wusir"
print(a.swapcase())     # 大小写转换

<4> String name .center (): center filled

a = "alex Wusir"
print(a.center(20,"*"))     # 居中 - 填充

<5> string name .find (): Find in the index by element lookup time is less than -1

a = "alex Wusir"
print(a.find("c"))        # 查找 通过元素查找索引,查找不到时返回-1

<6> string name .index (): Search Search index through the elements, when it can not find the error

a = "alex Wusir"
print(a.index("c"))       # 查找 通过元素查找索引,查找不到时就报错

<7> "splicing element" .join ([ "1", "2", "3"]): splicing the list into a string (int type can not be directly spliced)

a = "alex Wusir"
print(a.join("_"))

lst = ["1","2","4"]
print("_".join(lst))  # 拼接,将列表转换成字符串

<8>str + str

name1 = "al"
name2 = "au"
print(id(name1))
print(id(name2))
print(id(name1 + name2))

<9> str * Digital

name1 = "al"
print(id(name1))
print(id(name1 * 5))

(Plus string operations, multiplication operations are opening up new space)

4. List: list

One list is a data type in Python, capable of storing a large number of different types of data. Called arrays in other languages. 32 is a restriction python 536,870,912 element 64 is limited python 1152921504606846975 elements. And the list is ordered, an index value, can be sliced, convenient value

4.1 define a list: lst = []

lst = [1,2,"alex",True,["钥匙","门禁卡",["银行卡"]]]
print(lst)

--- a list of vessel

The list is an ordered container support index

Is a list of variable data type in situ modification

Element is a comma-separated list

4.2 index list

And also has a list of strings as index:

lst = ['刘德华','周润发','周杰伦','向华强']
print(lst[0])  # 列表中第一个元素
print(lst[1])  # 列表中第二个元素
print(lst[2])  # 列表中第三个元素

Note: The list can be modified, and the string is not the same here

lst[3] = '王健林'
print(lst)

Modify the string

s = '王思聪'
s[0] = '李'
print(s)
结果:
Traceback (most recent call last):
  File "D:/python_object/path2/test.py", line 1076, in <module>
    s[0] = '李'
TypeError: 'str' object does not support item assignment

List of sections 4.3

lst = ["麻花藤", "王剑林", "马芸", "周鸿医", "向华强"] 
print(lst[0:3])     # ['麻花藤', '王剑林', '马芸'] 
print(lst[:3])      # ['麻花藤', '王剑林', '马芸']
print(lst[1::2])    # ['王剑林', '周鸿医'] 也有步长 
print(lst[2::-1])   # ['马芸', '王剑林', '麻花藤'] 也可以倒着取 
print(lst[-1:-3:-2])    # 倒着带步长

4.4 List of increase:

<1> append (): append add append (additional content) at the end of most places

lst = [1,2,3,4,3]
lst.append(13)   # 追加  在最末尾的地方进行添加print(lst)

<2> insert (): Insert insert (insertion position, "inserted content") to minimize the use, causes reduced efficiency

lst = [1,2,3,4,3]
lst.insert(2,"ro")       # 插入
print(lst)

<3> extend (): Add a recursive addition a

lst = [1,2,3,4,3]
lst.extend([1,2,3,4])       # 迭代添加(一个一个添加)
print(lst)

4.5 List Delete:

<1> remove (): Only a delete, delete from left to right. Delete elements by name

lst = [1,2,3,4,3]
list.remove(1)    
print(lst)

<2> pop (): Delete the last pop-up default, and has a return value, the return value is the pop. You can also add index delete pop (3). Repr (): View the current source of ecological data

lst = [1,2,3,4,3]
print(repr(lst.pop(2)))    # repr()查看当前数据的原生态
print(lst)

<3> clear (): Clear

lst = [1,2,3,4,3]
lst.clear()             # 清空
print(lst)

<4> del (): Delete directly in the memory space. Can be deleted by the index, slice, step

lst = [1,2,3,4,3]
del lst[4]    # 通过索引删除
del lst[2:5]    # 通过切片删除
del lst[1:5:2]      # 通过步长删除
print(lst)

4.6 modify the list:

<1> lst [2] = 80: modified by an index

lst = [1,2,3,4,5]
lst[2] = 80    # 通过索引进行修改
print(lst))

<2> Lst [1: 3] = "skaj": modified by dicing, the object must be iterative. The default step 1, modify the content can be more or less

lst = [1,2,3,4,5]
lst[1:3] = "20"  # 通过切片进行修改,默认步长为1,修改的内容必须是可迭代的对象,修改的内容可多可少
print(lst)

<3> Lst [1: 5: 2] = "10": when modified by the step, the step is not a necessary correspondence

lst = [1,2,3,4,5]
lst[1:5:2] = 100,100    # 步长不为1的时候,必须一一对应print(lst)

4.7 List Find:

<1> through the index to find

<2> for loop

lst = [1,2,3,4,5]
    for i in lst:
        print(i)

4.8 nested list:

lst = [1,2,[3,4,5,["alex[]",True,[[1,2,]],90],"wusir"],"taibai"]
lst1 = lst[2]   # [3, 4, 5, ['alex[]', True, [[1, 2]], 90], 'wusir']
lst2 = lst1[3]  # ['alex[]', True, [[1, 2]], 90]
str_1 = lst2[0]
print(str_1[-1])
print(lst[2][3][0][-1])

Find layer by layer, [......] as an element

4.9 list data type methods - added:

<1> defined lists: list ( "123456")

<2> Method list:

1> list name .index (): Finds the index through the elements
lst = [1,23,4,5,7,8,9]
print(lst.index(4))        # 通过元素查找索引
2> list name .reverse (): Reverse
lst = [1,23,4,5,7,8,9]
lst.reverse()     
print(lst)
3> list name .sort (): The default sort is ascending
lst = [1,23,4,5,7,8,9]
lst.sort()                 # 排序 默认是升序
print(lst)
4> list name .sort (reverse = True): Descending
lst = [1,23,4,5,7,8,9]
lst.sort(reverse=True)     # 降序
print(lst)

Questions:

lst = [1,[]] * 5
 print(lst)       # [1, [], 1, [], 1, [], 1, [], 1, []]
 lst[1].append(6)
 print(lst)       # [1, [6], 1, [6], 1, [6], 1, [6], 1, [6]]
Multiplication is performed when the list of elements are common to

5, the tuple: tuple

Tuple is one of the data types in Python, it is ordered, immutable, only support queries. Tuple is an immutable list.

5.1 Definitions manner: Tu = (1,2,3)

tu = (1,2,"alex",[1,3,4])
print(tu)

5.2 yuan group of statistics:

.Count tuple ()

tu = (1,2,3,4,5,1,2,1)
print(tu.count(1))

5.3 yuan Group Gets the index:

Tuple .index (4): Query by element index

tu = (1,2,3,4,5,1,2,1)
print(tu.index(2))  # 通过元素查询索引

5.4 yuan group purposes:

Use the configuration file

5.5 yuan nested group:

tu = (1,2,3,4,(5,6,7,8,("alex","wusir",[1,23,4])))
print(tu[4][4][0])

(3)Tuple:

Questions:

  tu = (1)
     \# tu1 = ("alex")
     \# tu2 = (1,)          #元组

5.6 tuple data type methods - added:

<1> you you +

tu = (12,3,4) + (4,5,3,4)
print(tu)

<2> tu * Digital

tu = (1,[]) * 3
print(tu)
tu[-1].append(10)
print(tu)
Tuple performing multiplication when the elements are common

6, dictionary - dict

Dictionary data structure is one of the Python, a disorder, a variable data type, all the operations by the key is the dictionary.

6.1 Definitions: dic = { "key": "value"} --- value pairs

6.2 dictionary function:

Store large amount of data, and the data associated with the data play a role

dic = {"10":"苹果手机",
       "11":"苹果手机",
       15:"小米手机",
       15:"华为手机",
       (1,):"oppo手机",
       }
print(dic)
Key: data type must be immutable (hashable), and a unique
Value: any variable (not hashed)

6.3 Dictionary of increase:

<1> violence added:

DIC [ "key"] = "value" // add the dictionary, a key-value pair is added
dic = {
       "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
       "炮手":"飞机",
       "豹哥":"贴膏药",
       "宝元":"宝剑",
       "alex":"吹牛逼"
}
dic["日阳"] = "小明"  # 字典的添加,添加的是一个键值对
dic["小妹"] = ["听歌","唱歌","吃","烤馕","大盘鸡","葡萄干"]
print(dic)
<2> dic.setdefault ( "key", [ "value 1", "Value 2"] // there is not added, no add:
First check whether there are key dictionary
There is no time to be added
dic = {
       "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
       "炮手":"飞机",
       "豹哥":"贴膏药",
       "宝元":"宝剑",
       "alex":"吹牛逼"
}
dic.setdefault("元宝",["唱","跳","篮球","喝酒"])
print(dic)

6.4 delete the dictionary:

<1> pop (): // pop value by deleting dictionary delete key, is the return of the deleted

dic = {
              "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
              "炮手":"飞机",
              "豹哥":"贴膏药",
              "宝元":"宝剑",
              "alex":"吹牛逼"
       }
print(dic.pop("宝元"))  #pop删除通过字典中的键进线删除 返回的也是被删除的值
print(dic)

<2> clear (): // Clear

dic = {
              "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
              "炮手":"飞机",
              "豹哥":"贴膏药",
              "宝元":"宝剑",
              "alex":"吹牛逼"
       }
dic.clear()      # 清空
print(dic)

<3> del dic: // delete the whole dictionary container

dic = {
              "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
              "炮手":"飞机",
              "豹哥":"贴膏药",
              "宝元":"宝剑",
              "alex":"吹牛逼"
       }
del dic          # 删除的是整个容器
print(dic)

<4> del dic [ "key"]: // delete key by

dic = {
              "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
              "炮手":"飞机",
              "豹哥":"贴膏药",
              "宝元":"宝剑",
              "alex":"吹牛逼"
       }
del dic["alex"]  # 通过键进行删除
print(dic)
Definition not remove

6.5 Dictionary of change:

<1> dic [ "key"] = "Value": // there is to cover, it is not added

dic = {
              "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
              "炮手":"飞机",
              "豹哥":"贴膏药",
              "宝元":"宝剑",
              "alex":"吹牛逼"
       }

dic["alex"] = "dsb"   # 有则就覆盖,没有添加
print(dic)

<2> update (new dictionary): // dictionary update function level above the back of the front dictionaries

dic = {
              "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
              "炮手":"飞机",
              "豹哥":"贴膏药",
              "宝元":"宝剑",
              "alex":"吹牛逼"
       }

dic1 = {"alex":"上过北大","wusir":"干过前端"}
dic1.update(dic)
print(dic1)

6.6 dictionary search:

<1> get ( "key"): // not query returns None get ( "key", "own specified content"): When the query can not return to their specified contents

dic = {
       "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
       "炮手":"飞机",
       "豹哥":"贴膏药",
       "宝元":"宝剑",
       "alex":"吹牛逼"
}

print(dic.get("alex"))   # 查询不到返回None
print(dic.get("元宝","找不到啊")) # 查找不到的时候返回自己制定的内容

<2> setdefault ( "key"): // can not find the time to return None

dic = {
       "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
       "炮手":"飞机",
       "豹哥":"贴膏药",
       "宝元":"宝剑",
       "alex":"吹牛逼"
}

print(dic.setdefault("alex"))  # 查询不到返回None

<3> dic [ "key"]: // can not find on the error

dic = {
       "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
       "炮手":"飞机",
       "豹哥":"贴膏药",
       "宝元":"宝剑",
       "alex":"吹牛逼"
}

print(dic["alex"])       # 查询不到就报错了

<4> dic.keys (): // Check key acquired list is a high imitation

dic = {
       "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
       "炮手":"飞机",
       "豹哥":"贴膏药",
       "宝元":"宝剑",
       "alex":"吹牛逼"
}

for i in dic:   # 查看所有的键
    print(i)

print(dic.keys())   # 获取到的是一个高仿列表

<5> dic.values ​​(): // Check value, the acquired list is a high imitation

dic = {
       "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
       "炮手":"飞机",
       "豹哥":"贴膏药",
       "宝元":"宝剑",
       "alex":"吹牛逼"
}

for i in dic:   # 查看所有的值
    print(dic.get(i))

print(dic.values()) # 获取到的是一个高仿列表

High imitation list of supported iteration does not support indexing

for i in dic.values(): # 高仿列表支持迭代
    print(i)

<6> items (): // view the key pair

dic = {
       "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
       "炮手":"飞机",
       "豹哥":"贴膏药",
       "宝元":"宝剑",
       "alex":"吹牛逼"
}
for i in dic.items():
    print(i[0],i[1])

6.7 nested dictionary:

Nested dictionary lookup time must be in accordance with layer by layer to find

dic = {

    101:{1:{"日魔":"对象"},
         2:{"隔壁老王":"王炸"},
         3:{"乔碧萝":("日魔","炮手","宝元")},
         },
    102:{1:{"汪峰":{"国际章":["小苹果","大鸭梨"]}},
         2:{"邓紫棋":["泡沫","信仰","天堂","光年之外"]},
         3:{"腾格尔":["隐形的翅膀","卡路里","日不落"]}
         },
    103:{1:{"蔡徐坤":{"唱":["鸡你太美"],
                   "跳":["钢管舞"],
                   "rap":["大碗面"],
                   "篮球":("NBA形象大使")}},

         2:{"JJ":{"行走的CD":["江南","曹操","背对背拥抱","小酒窝","不潮不花钱"]}},
         3:{"Jay":{"周董":["菊花台","双节棍","霍元甲"]}}},

    201:{
        1:{"韦小宝":{"双儿":"刺客","建宁":{"公主":{"吴三桂":"熊"}},"龙儿":{"教主老婆":"教主"}}}
    }
}

print(dic[201][1]["韦小宝"]["建宁"]["公主"]["吴三桂"])
print(dic[103][1]["蔡徐坤"]["跳"][0][1])
print(dic[102][2]["邓紫棋"][1])

6.8 dict data type methods - added:

<1> dictionary name .popitem (): random delete, and returns the deleted key to delete the last version of a key-value pair Python3.6

dic = {"key":1,"key1":2,"key2":4,"key3":1}
print(dic.popitem())   # 随机删除  python3.6版删除最后一个键值对    # popitem返回的是被删除的键值对
print(dic)

<2> name dictionary .fromkeys ( "abc", []): Bulk create key-value for "a": [], "b": [], "c": []

Questions:

dic = {}
     dic.fromkeys("abc",[])   # 批量创建键值对 
     print(dic)
fromkeys first argument must be an iterative object, the object will be iterative iterate become dictionary keys. The second parameter is the value (this value is common)
fromkeys common variable data values ​​will pit type, immutable data types on the right
dic = {}
dic = dic.fromkeys("abc",[])
print(dic)
dic["b"] = 11
dic["a"].append(10)
print(dic)

7, the collection:

One set of data types in Python, is disordered, and the only variable. Dictionary is a collection of no value to the collection of natural weight.

Questions: single line of code to heavy

lst = [1,223,1,1,2,31,231,22,12,3,14,12,3]
print(list(set(lst)))

7.1 defines an empty set: set1 = set {}

7.2 collection by:

<1> set name .add ()

s = set()
s.add("alex")
print(s)

<2> collection name .update (): Adding Iteration

s = set()
s.update("wusir")  # 迭代添加
print(s)

7.3 collection of deleted:

<1> collection name .remove (): Delete by elements

s = {100,0.1,0.5,1,2,23,5,4}
s.remove(4)    # 通过元素删除
print(s)

<2> collectionname .clear (): Clear

s = {100,0.1,0.5,1,2,23,5,4}
s.clear()  # 清空
print(s)

<3> set name .pop (): Delete forthwith (typically the smallest)

s = {100,0.1,0.5,1,2,23,5,4}
s.pop()      # 随机删除 (一般是最小的)
print(s)

7.4 set changes:

After the first cut plus

s = {1,2,3,4,5}              # 先删后加

7.5 set of search:

for loop

Other operations 7.6 collection:

(1) Set the difference -

s = {1,23,9,4,5,7}
s1 = {1,2,3,4,5}

print(s - s1)
print(s1 - s)

(2) the intersection &

s = {1,23,9,4,5,7}
s1 = {1,2,3,4,5}

print(s & s1)

(3) union |

s = {1,23,9,4,5,7}
s1 = {1,2,3,4,5}

print(s | s1)

(4) Anti intersection ^

s = {1,23,9,4,5,7}
s1 = {1,2,3,4,5}

print(s ^ s1)

(5) a subset <: returns a Boolean value

s = {1,23,9,4,5,7}
s1 = {1,2,3,4,5}

print(s < s1)

(6) Set the parent (super)>:

s = {1,23,9,4,5,7}
s1 = {1,2,3,4,5}

print(s1 > s)

(7) to freeze the collection frozenset

s = {1,23,9,4,5,7}
s1 = {1,2,3,4,5}

dic = {frozenset({1,23,4,5}):123}
print(dic)

Guess you like

Origin www.cnblogs.com/caiyongliang/p/11408782.html