python string dictionary and the foundation of the collection set

A, String string

1. Split and Merge

1.1 str1.split(str2, num)

Function: str2 string taken as the split, num default str1.count ()

If after a given num, num string is taken, the remaining no longer taken.

str1 = "how are you , i am fine thank you"
#使用空格进行分割
list1 = str1.split(" ")
print(list1)
#结果
['how', 'are', 'you', ',', 'i', 'am', 'fine', 'thank', 'you']

1.2 str1.splitlines ([notch ends])

Function: string in rows ( '\ r', '\ r \ n', '\ n') is divided, returns a list of elements as each row, if the value of the parameter keepends False, no line breaks, If True, the reserved line breaks.

str2 = '''how are
you ?
i am
fine
!
'''

list2 = str2.splitlines()
print(list2)
#结果
['how are', 'you ?', 'i am', 'fine', '!']
str2 = '''how are
you ?
i am
fine
!
'''

list2 = str2.splitlines(keepends=True)
print(list2)
#结果
['how are\n', 'you ?\n', 'i am\n', 'fine\n', '!\n']

1.3 str1.join(seq)

Function: a specified character string as a separator, all the elements in seq merged into a new string

list2 = ['you', 'are', 'very', 'great', '!']
str3 = ' '.join(list2)
print(str3)
#结果
you are very great !
str1 = "how are you , i am fine thank you"
str3 = "*".join(str1)
print(str3)
#结果
h*o*w* *a*r*e* *y*o*u* *,* *i* *a*m* *f*i*n*e* *t*h*a*n*k* *y*o*u

Note: If the connection is a string, it will use for each character in the string of characters specified connection.

2. Get the maximum and minimum character

2.1 max(str)

Function: Returns the string str in the largest letters

str1 = "how are you , i am fine thank you"
print(max(str1))
#结果
y

2.2 min (str)

Function: Returns the minimum letter string str

str1 = "how are you , i am fine thank you"
print(min(str1))
#结果
‘ ’

Note: The comparison is ASCII value

3. Alternatively string

3.1 replace(old , new [, count])

Function: the old string replace new, if not specified for the count, all default Alternatively, count if the Prev specified count, then after replacement

str1 = "how are you , i am fine thank you"
str2 = str1.replace("you" ,'me')
print(str2)
#结果
how are me , i am fine thank me

3.2 Mapping replacement string

A parameter: Character to be converted parameters II: the target character

Dic = Strkmketrans (Oldstr, Newstr)

str2.translate(dic)

str5 = "aaa bbb  ccc  deee"
dic = str5.maketrans("ac", "21")
# a--2   c--1
str7 = "how  are you  ,u ewe "
print(str7.translate(dic))
#结果
how  2re you  ,u ewe 
#注意:很少用
4. Analyzing the end of the beginning of the string

str.startswith(str1, start=0, end=len(str))

Function: within the given range is determined whether the character string beginning with a given string, if not specified range, the entire string Default

str1 = "aaa bbb  ccc  deee"
print(str1.startswith("aa"))
#结果
True


str1 = "aaa bbb  ccc  deee"
print(str1.startswith("aa", 3, 9))
#结果
False

str.endswith(str, start=0, end=len(str))

Function: within the given range is determined whether the string ends with the specified string, if the range is not specified, the default is the entire string

str1 = "aaa bbb  ccc  deee"
print(str1.endswith("e"))
#结果
True

str1 = "aaa bbb  ccc  deee"
print(str1.endswith("e", 3 ,9))
#结果
False
The encoding and decoding

str.encode(encoding=”utf-8”, errors=”scrict”)

Function: a character string encoded, if not specified, the default selection encoding utf-8

str1 = "你好吗?"
data = str1.encode()
print(data)
print(type(data))
#结果
b'\xe4\xbd\xa0\xe5\xa5\xbd\xe5\x90\x97\xef\xbc\x9f'
<class 'bytes'>

str.decode(encoding=”utf-8”)

“hello”.encode(“utf-8”).decode()

Function: a character decoding, without specifying the encoding format, selected by default utf-8

str1 = "你好吗?"
data = str1.encode()
print(data)
print(type(data))

data2 = data.decode()
print(data2)
print(type(data2))

#结果
b'\xe4\xbd\xa0\xe5\xa5\xbd\xe5\x90\x97\xef\xbc\x9f'
<class 'bytes'>
你好吗?
<class 'str'>

Note: The encoding format decoding to be consistent with the remains of coding

Expansion: errors = ignore time, ignore the error

6. determines whether a letter or digit

Strkislf ()

Function: to determine at least one character string, and all characters are letters, if it is true then return True, otherwise False

str8 = "hello ni hao "
print(str8.isalpha())
#结果
False
str9 = "hellonahao"
print(str9.isalpha())
#结果
True

str.isalnum ()

Function: to determine a string of at least one character, and all characters are letters or digits returns True and False otherwise

str10 = "sc22xdcd"
print(str9.isalnum())
print(str10.isalpha())
#结果
True
False
7. Analyzing the case

str.isupper ()

Function: If the string contains at least one character letters, and these letters are capitalized, then return True, otherwise False

str10 = "AA2221  111"
print(str10.isupper())
#结果
True

str10 = "AAaaa"
print(str10.isupper())
#结果
False

str.islower()

Function: If the string contains at least one letter character, and that all the letters are lowercase, True is returned, otherwise returns False

str10 = "aa2221  111"
print(str10.islower())
#结果
True
8. Analyzing contain special characters

8.1 str.istitle ()

Function: If a string is the title of returns True, otherwise False

[Title] capitalize the first letter of each

str1 = "Hello World"
print(str1.istitle())

8.2 Strkisdigit ()

isdigit()
True: Unicode数字,byte数字(单字节),全角数字(双字节),罗马数字
False: 汉字数字
Error: 无
print("123".isdigit())
print("123a".isdigit())
#结果
True
False

Ditto

str.isnumeric()

Function: If the string contains only numeric characters, it returns True, otherwise False

isnumeric()
True: Unicode数字,全角数字(双字节),罗马数字,汉字数字
False: 无
Error: byte数字(单字节)

8.3 str.isdecimal ()

Function: Check whether the string contains only the decimal character, if it returns True, otherwise False

isdecimal()
True: Unicode数字,,全角数字(双字节)
False: 罗马数字,汉字数字
Error: byte数字(单字节)
print("123".isdecimal())
print("123z".isdecimal())
#结果
True
False
num = "1"  #unicode
num.isdigit()   # True
num.isdecimal() # True
num.isnumeric() # True

num = "1" # 全角
num.isdigit()   # True
num.isdecimal() # True
num.isnumeric() # True

num = b"1" # byte
num.isdigit()   # True
num.isdecimal() # AttributeError 'bytes' object has no attribute 'isdecimal'
num.isnumeric() # AttributeError 'bytes' object has no attribute 'isnumeric'

num = "IV" # 罗马数字
num.isdigit()   # True
num.isdecimal() # False
num.isnumeric() # True

num = "四" # 汉字
num.isdigit()   # False
num.isdecimal() # False
num.isnumeric() # True

8.4 str.isspace ()

Function: If the string contains only spaces, returns True, otherwise False

print(" ".isspace())
print("\t".isspace())
print("\n".isspace())
print("\r".isspace())
print("  qq".isspace())

#结果
True
True
True
True
False
9.ASCII code conversion

9.1 words (str)

Function: Get string represents an integer of ASCII value

print(ord("A"))
print(ord("你"))
#结果
65
20320

9.2 chr(str)

Converted into the corresponding coded character

print(chr(68))
print(chr(20190))
#结果
D
仞

Two, dict dictionary

1 Overview

dict is also a storage, and similar tuple list, however, using the dictionary key - value (key-value) stored in the form

Advantages: fast search speed

2.key features

1. The key must be unique in the dictionary

2.key must be immutable objects

For example: string, integer, etc. are immutable, as key

list is variable, not as a key

Thinking: Saving a class in the shoes of results

Thinking 1: list or tuple, but do not easily occur on the disorder No.

Ideas 2: Use the two-dimensional list or tuple, but will be slower

3 ideas: dictionary can be used, the number of students or school name as a key, value score for storage, easy to find

3. Create a dictionary

grammar:

Dictionary key name = {1: 1 value, the key 2: value of 2, ...}

dist1 = {'tom':90,'lili':78, 'lele':92}
print(dist1)
4. Operation Dictionary

4.1 Accessing element

Syntax: element name = dictionary [key]

dist1 = {'tom':90,'lili':78, 'lele':92}
print(dist1['tom'])

Note: In the case of key does not exist, will complain

Syntax: element = dictionary .get (key)

Function: using the get method to get the value, if the key is present, the value of the value is returned if the key does not exist is returned None

dist1 = {'tom':90,'lili':78, 'lele':92}
value = dist1.get('tom')
print(value)

4.2 Adding elements

Syntax: Dictionary name [key] = value

dist1 = {'tom':90,'lili':78, 'lele':92}
dist1['lisi'] = 89
print(dist1)

Note: a key corresponds to only one value, many times the value of a key assignment foregoing values ​​will be overwritten later.

4.3 Removing elements

Syntax: Dictionary name .pop (key)

dist1 = {'tom':90,'lili':78, 'lele':92}
dist1.pop('tom')
print(dist1)
5. traversal dictionary

5.1 for loop iterates

grammar:

Get key

for key in dist:

​ print(key)

Get the value

for value in dist.values() :

​ print(value)

At the same time get the keys and values

for k, v in dist.items() :

print (k, v)

Note: Dictionaries are unordered, stored in memory is disordered and therefore can not be obtained by the value of the subscript

dist1 = {'tom':90,'lili':78, 'lele':92}
#获取字典的key
for key in dist1:
    print(key)
#获取字典中的value    
for value  in dist1.values():
    print(value)
#同时获取字典中的key与value
for k, v  in dist1.items():
    print(k, v)
6. The difference with the list of

1.dist find and insert the fast speed, it will not increase the key-value becomes slow, but when looking at the list one by one from scratch backwards through the elements, and when the amount of data increases, the speed also as will be slow

2.dist take a lot of memory, memory and more waste, but list only the equivalent of storing a dictionary key or value part, and closely spaced data.

Three, set collection

1 Overview

dist similar set and the set is a set of key, but with the difference that the set is not stored dist value

Essence: unordered set of elements and no repeat

2.set creation

grammar:

set1 = set([1, 2, 3, 4, 5])

Note: Create a list or set need dist tuple or as an element of the input set, will automatically duplicate filters in the set

s1 = set([1, 2, 3, 4, 5])
print(s1)
3.set operation

3.1 set.add()

note:

1. You can add duplicate elements, but there will be no effect

2.add elements can not be a list or dictionary, because they are variable

s1 = set([1, 2, 3, 4, 5])
s1.add(6)
s1.add((2, 3, 4))
print(s1)
#结果
{1, 2, 3, 4, 5, 6, (2, 3, 4)}

3.2 set.update()

Function: insert the whole list, tuple, breaking the string inserted

Note: You can not directly into digital

s1 = set([1, 2, 3, 4, 5])
s1.update([4,"anam","hha"])
s1.update("hello")
print(s1)
#结果
{1, 2, 3, 4, 5, 'anam', 'l', 'o', 'h', 'e', 'hha'}

3.3 set.remove (element)

Function: Removing elements

s1 = set([1, 2, 3, 4, 5])
s1.remove(3)
print(s1)

3.4 traversing element

grammar:

for i in set :

print(i)

Note: set is unordered, and therefore can not be acquired by the subscript element

for index, data in enumerate(set):

​ print(index, data)

By this way, to forcibly add a suffix

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

for index,data in enumerate(s1):
    print(index, data)

3.5 intersection and union

grammar:

Intersection newest = set1 & set2

Union newest = set1 | set2

s1 = set([1, 2, 3, 4, 5])
s2 = set([4, 5, 6, 7])
s3 = s1 & s2
s4 = s1 | s2
print(s3)
print(s4)
#结果
{4, 5}
{1, 2, 3, 4, 5, 6, 7}

Fourth, the type conversion

The main tool for many of the storage: list, tuple, dict, set

Special features: dict is used to store key-value pairs

4.1 list converted to set
l1 = [1, 2, 4, 5]
s1 = set(l1)
print(type(s1))
print(s1)

4.2 tuple converted to set

t1 = (1, 2, 3, 4)
s1 = set(t1)
print(type(s1))
print(s1)

4.3 set is converted to list

s1 = set([1, 2, 3, 4])
l1 = list(s1)
print(type(l1))
print(l1)

4.4 set is converted into tuple

s1 = set([1, 2, 3, 4])
t1 = tuple(s1)
print(type(t1))
print(t1)

Fifth, the iterator

List of Formula

grammar:

list = [result for x in range(m, n)]

Demand: Creating a [1, 2, ... 100] List

>>> range(1, 101)
[1, 2, 3, 4, 5,...,100]

Requirement 2: Generate a [1x1, 2x2, 3x3, ... .100x100] list

>>> list1 = []
>>> for x in range(1, 101)
        list1.append(x*x)
>>> list1
[1, 4, 9,....10000]

#使用列表生成式,可以这么来写
>>> list2 = [x*x for x in range(1, 101)]

Nature: Mandatory for loop is to unload line, and the result is written in the input front, the result of using [] quotes

5.1 iterables

1. can directly act directly on the object for circulation collectively referred to as iterables, we call: Iterator

2. We can use isintance () to determine whether an object is an object Iterator

3. The for loop can act directly on the type of data are the following

a set of data types: As list, tuple, dict, set and string

b generator (generator):. iterator to return is a function, in fact, is the definition of an iterative algorithm it can be understood as a special iterator.

Builder:

List by the formula, we can directly create a list, however, subject to memory limitations, the list is certainly limited capacity, if we only need to access the first few elements, if the list element can be calculated according to an algorithm out, that if we can during the cycle of constantly calculate the subsequent elements? This eliminates the need to create a complete list, thus saving a lot of space. In Python, while circulating mechanism for this calculation, known as a generator (Generator)

#要创建一个generator,有很多种方法。第一种方法很简单,只要把一个列表生成式的[]改成(),就创建了一个generator
>>> g = (x for x in range(1, 101))
>>> g
<generator object <genexpr> at 0x10124df68>
>>> g.__next__()
1
>>> [x for x in g]
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]

NOTE: When using Iterator determining packages need to import Iterable

from collections import Iterable

print(isinstance([],Iterable))
print(isinstance((),Iterable))
print(isinstance({},Iterable))
print(isinstance("",Iterable))
print(isinstance((x for x in range(10)),Iterable))
print(isinstance(1,Iterable))
#结果
True
True
True
True
True
False
5.2 iterator

Iterator: not only can act on a for loop, you can be next () function continues to call and returns the next value, until the last StopIteration error, said it could not return the next value

May be next () function returns the next call and continue to be a worthy subject iterator (Iterator objects)

You can use the isinstance () function to determine whether an object is an object Iterator

print(isinstance([],Iterator))
print(isinstance((),Iterator))
print(isinstance({},Iterator))
print(isinstance("",Iterator))
# 只有这个是迭代器
print(isinstance((x for x in range(10)),Iterator))

#结果
False
False
False
False
True
5.3 Iterator conversion

By Iter () function list, tuple, dict, string objects convert Iterator

>>> a = iter([1, 2, 3, 4, 5])
>>> print(next(a))
1
print(isinstance(iter([]), Iterator))
print(isinstance(iter(()), Iterator))
print(isinstance(iter({}), Iterator))
print(isinstance(iter(''), Iterator))
#结果
True
True
True
True
Published 31 original articles · won praise 4 · Views 3520

Guess you like

Origin blog.csdn.net/qq_29074261/article/details/80016686