In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article focuses on "example usage of python advanced variable types". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "the example usage of python advanced variable types".
Advanced variable type goal
List
Tuple
Dictionaries
String
Public method
Variable advanced
Review of knowledge points
Data types in Python can be divided into digital type and non-digital type.
Digital type
Integer (int)
Floating point (float)
Boolean (bool)
True True is not a zero number-- either zero or true
Fake False 0
Plural (complex)
Mainly used for scientific calculation, such as plane field problems, wave problems, inductance and capacitance problems, etc.
Non-digital type
String
List
Tuple
Dictionaries
In Python, all non-numeric variables support the following features:
It is a sequence sequence, which can also be understood as a container.
Value []
Traversing for in
Calculate length, maximum / minimum, compare, delete
Slice
Link + and repeat *
01. Listing 1.1 definition of the list
List (list) is the most frequently used data type in Python and is often called an array in other languages.
Specially used to store a string of information
The list is defined by [], the data is used, separated.
The index of the list starts at 0
An index is the location number of the data in the list, and the index can be called a subscript.
Note: when taking a value from a list, if it is out of the index range, the program will report an error
Name_list = ["zhangsan", "lisi", "wangwu"] 1.2 list common operations
Define a list in ipython3, for example: name_list = []
Enter name_list. Press the TAB key, and ipython prompts you that the list can use the following methods:
In [1]: name_list.name_list.append name_list.count name_list.insert name_list.reversename_list.clear name_list.extend name_list.pop name_list.sortname_list.copy name_list.index name_list.remove serial number classification keyword / function / method description 1 add list. Insert (index Data) insert data at the specified location-list .append (data) append data at the end-list .extend (listing 2) append data from list 2 to list 2 modify list [index] = data modify data at specified index 3 delete del list [index] delete data at specified index-list .remove [data] delete first Specified data that appears-list .pop delete end data-list .pop (index) deletes specified index data-list .clear empty list 4 Statistics len (list) list length-list .count (data) number of times the data appears in the list. Sort () ascending sort-list .sort ( Reverse=True) sort in descending order-list. Reverse () reverse, Reverse del keyword (popular science)
You can also delete elements in a list by using the del keyword (delete)
The del keyword is essentially used to delete a variable from memory.
If you use the del keyword to remove a variable from memory, subsequent code can no longer use the variable
Del name_list [1]
In daily development, to delete data from the list, it is recommended to use the methods provided by the list
Keywords, functions and methods (popular science)
Keywords are Python built-in identifiers with special meaning
In [1]: import keywordIn [2]: print (keyword.kwlist) In [3]: print (len (keyword.kwlist))
Keyword does not need to be followed by parentheses
Function encapsulates independent functions and can be called directly
Function name (parameter)
Functions need to be memorized
Method is similar to a function, but also encapsulates independent functions.
Method needs to be called through an object to represent the action to be done on this object
Object. Method name (parameter)
Enter. After the variable, and then select the action to be performed on the variable, which is much easier to remember than the function
1.3 Loop traversal
Traversal is to get data from the list from beginning to end.
Do the same for each element within the body of the loop
In order to improve the efficiency of list traversal in Python, iterative iteration traversal is specially provided.
Iterative traversal can be achieved using for
# in list variables used inside the for loop for name in name_list: operate on list elements inside the loop print (name)
1.4 Application scenario
Although different types of data can be stored in the Python list
But in development, more application scenarios are
The list stores the same type of data
Through iterative traversal, the same operation is performed within the loop body for each element in the list
02. Definition of tuple 2.1 tuple
A Tuple is similar to a list, except that the elements of a tuple cannot be modified
A tuple represents a sequence of elements
Tuples have specific application scenarios in Python development.
Used to store a string of information, used between data, separated
Tuples are defined with ()
The index of the tuple starts at 0
The index is the location number of the data in the tuple
Info_tuple = ("zhangsan", 18,1.75) when creating an empty tuple info_tuple = () tuple contains only one element, you need to add a comma info_tuple = (50,) 2.2 tuple common operation after the element
Define a tuple in ipython3, for example: info = ()
Enter info. Press the TAB key, and ipython will prompt you that the tuple can use the following functions:
Info.count info.index2.3 loop traversal
The value is to get the data stored in the specified location from the tuple.
Traversal is to get data from tuples from beginning to end.
# variable in tuple for item in info used inside the for loop: operate on tuple elements inside the loop print (item)
In Python, you can use for to loop through all non-numeric variables: lists, tuples, dictionaries, and strings
Tip: in actual development, unless you can confirm the data types in tuples, there are not many requirements for loop traversal of tuples.
2.4 Application scenario
Although you can use for in to traverse tuples
But in development, more application scenarios are:
The parameters and return values of a function. A function can receive any number of parameters or return more than one data at a time.
Format string, the () after the format string is essentially a tuple
Make the list unmodifiable to protect data security
Info = ("zhangsan", 18) print (age of "% s is% d"% info) conversion between tuple and list
Use the list function to convert tuples into lists
List (tuple)
You can convert a list to a tuple using the tuple function
Tuple (list) 03. Dictionary 3.1 definition of dictionaries
Dictionary (dictionary) is the most flexible data type in Python besides lists.
Dictionaries can also be used to store multiple data
Usually used to store relevant information describing an object
The difference between and the list
A list is an ordered collection of objects
A dictionary is an unordered collection of objects
Dictionaries are defined with {}
Dictionaries use key-value pairs to store data, use between key-value pairs, separate
Key key is the index
The value value is data
Use: separation between key and value
The key must be unique
Values can take any data type, but keys can only use strings, numbers, or tuples
Xiaoming = {"name": "xiaoming", "age": 18, "gender": True, "height": 1.75} 3.2 Dictionary common operations
Define a dictionary in ipython3, for example: xiaoming = {}
Enter xiaoming. Press the TAB key and ipython will prompt you that the dictionary can use the following functions:
In [1]: xiaoming.xiaoming.clear xiaoming.items xiaoming.setdefaultxiaoming.copy xiaoming.keys xiaoming.updatexiaoming.fromkeys xiaoming.pop xiaoming.valuesxiaoming.get xiaoming.popitem
3.3 Loop traversal
Traversal is to get all the key-value pairs from the dictionary in turn.
# the variable `in dictionary for k in xiaoming:print of `key used inside the for loop ("% s:% s"% (k, xiaoming [k]))
Tip: in the actual development, because each key value in the dictionary is different for the type of data stored, there are not many requirements for the loop traversal of the dictionary.
3.4 Application scenario
Although you can use the for in traversal dictionary
But in development, more application scenarios are:
Use multiple key-value pairs to store relevant information that describes an object-- describe more complex data information
Put multiple dictionaries in a list, then traverse them, and do the same for each dictionary inside the loop body.
Card_list = [{"name": "Zhang San", "qq": "12345", "phone": "110"}, {"name": "Li Si", "qq": "54321", "phone": "10086"}] 04. String 4.1 definition of string
A string is a string of characters, a data type that represents text in a programming language.
In Python, you can define a string using a pair of double quotes "or a pair of single quotes"
Although you can use\ "or\'to escape a string, in actual development:
If you need to use "inside the string, you can use'to define the string.
If you need to use 'inside the string, you can use define string
You can use the index to get the characters at a specified position in a string, with the index count starting at 0
You can also use for to loop through each character in a string
Most programming languages use "to define strings."
String = "Hello Python" for c in string: print (c)
4.2 Common operations of strings
Define a string in ipython3, for example: hello_str = ""
Enter hello_str. Press the TAB key, and ipython prompts you that the string can be used in the following ways:
In [1]: hello_str.hello_str.capitalize hello_str.isidentifier hello_str.rindexhello_str.casefold hello_str.islower hello_str.rjusthello_str.center hello_str.isnumeric hello_str.rpartitionhello_str.count hello_str.isprintable hello_str.rsplithello_str.encode hello_str.isspace hello_str.rstriphello_str.endswith hello_str.istitle hello_str. Splithello_str.expandtabs hello_str.isupper hello_str.splitlineshello_str.find hello_str.join hello_str.startswithhello_str.format hello_str.ljust hello_str.striphello_str.format_map hello_str.lower hello_str.swapcasehello_str.index hello_str.lstrip hello_str.titlehello_str.isalnum hello_str.maketrans hello_ Str.translatehello_str.isalpha hello_str.partition hello_str.upperhello_str.isdecimal hello_str.replace hello_str.zfillhello_str.isdigit hello_str.rfind
Tip: it is because python provides enough built-in methods that you can manipulate strings more flexibly when developing! Respond to more development needs!
1) judging type-9 method indicates that string.isspace () returns Truestring.isalnum () if string contains only spaces, returns Truestring.isalpha () if string has at least one character and all characters are letters or numbers, returns Truestring.isdecimal () if string has at least one character and all characters are letters, returns True if string contains only numbers, string.isdigit () returns True if string contains only numbers Full-width numbers, ⑴,\ u00b2string.isnumeric () return True if string contains only numbers, full-width digits, Chinese numerals string.istitle () return Truestring.islower () if string is themed (the first letter of each word is uppercase) if string contains at least one case-sensitive character, and all these (case-sensitive) characters are lowercase Returns Truestring.isupper () if the string contains at least one case-sensitive character, and all these (case-sensitive) characters are uppercase, return True2) find and replace-7 method indicates that string.startswith (str) checks whether the string begins with str, yes, returns Truestring.endswith (str) to check whether the string ends with str. Yes, return Truestring.find (str, start=0, end=len (string)) to check whether str is included in string. If start and end specify a range, check whether it is included in the specified range. If it returns the starting index value, otherwise-1string.rfind (str, start=0, end=len (string)) is similar to find (), but starting from the right to find string.index (str, start=0, end=len (string)) is similar to the find () method. However, if str is not in string, string.rindex (str, start=0, end=len (string)) is similar to index (), except that string.replace (old_str, new_str, num=string.count (old)) replaces old_str in string with new_str if num specifies Then replace no more than num 3) uppercase conversion-5 method indicates that string.capitalize () uppercase string.title () converts the first letter of each word in the string to lowercase string.lower () converts all uppercase characters in string to lowercase string.upper () converts lowercase letters in string to uppercase string.swapcase () flips uppercase and lowercase 4) text alignment-3 method says Bright string.ljust (width) returns a left alignment of the original string The new string string.rjust (width) filled with spaces to the length width returns a right alignment of the original string, and the new string string.center (width) filled with spaces to the length width returns the center of the original string. And use blanks to fill the new string of length width 5) remove white space characters-3 method string.lstrip () truncate the white space characters on the left (beginning) of string () truncate the white space characters on the right (end) of string string.strip () truncate the white space characters on the left and right sides of string 6) split and concatenate-5 method explains that string.partition (str) divides the string string into a 3-element tuple (before str, str) (after str) string.rpartition (str) is similar to the partition () method Just start from the right to find string.split (str= "", num) split string with str as the delimiter. If num has a specified value, only num + 1 substrings are separated. By default, str contains'\ r','\ t','\ n 'and space string.splitlines () separated by line ('\ r','\ n','\ r\ n') Returns a list of lines as elements string.join (seq) merges all elements in seq into a new slice of the string 4.3 string with string as the delimiter
Slicing method is suitable for strings, lists, and tuples
Slices use index values to limit the range, cutting out small strings from a large string
Lists and tuples are ordered collections, and the corresponding data can be obtained through index values.
A dictionary is an unordered collection that uses key-value pairs to save data.
String [start index: end index: step size]
Note:
The specified interval belongs to the left closed and right open type [start index, end index) = > start index > = range
< 结束索引 -------从 起始 位开始,到 结束位的前一位 结束(不包含结束位本身) 从头开始,开始索引 数字可以省略,冒号不能省略 到末尾结束,结束索引 数字可以省略,冒号不能省略 步长默认为 1,如果连续切片,数字和冒号都可以省略 索引的顺序和倒序 在 Python 中不仅支持 顺序索引,同时还支持 倒序索引 所谓倒序索引就是 从右向左 计算索引 最右边的索引值是 -1,依次递减Exercise
Intercept a string from position 2 to 5
Intercept a string from 2 to the end
Intercept a string from the starting position of ~ 5
Intercept the complete string
Intercept a string every other character from the start position
Starting with index 1, take one for every other one
Intercept a string from 2 to end-1
Intercept the last two characters of a string
The reverse order of strings (interview questions)
The answer num_str = "0123456789" # 1. Intercept the string print (num_str [2:6]) # 2 from positions 2-5. Intercept the string print (num_ str2:]) # 3 from the end of 2 ~ ``. Intercept the string print (num_str [: 6]) # 4 starting from `~ 5. Intercept the complete string print (num_str [:]) # 5. Intercept the string print (num_str [:: 2]) # 6 every other character from the start position. Starting with index 1, every other print (num_ str1: 2) # inverted slice #-1 represents the penultimate character print (num_str [- 1]) # 7. Intercept the string print (num_ stre [2:-1]) # 8 from the end of 2 ~ `. Intercept the last two characters of the string print (num_str [- 2:]) # 9. Reverse order of strings (interview questions) print (num_str [::-1]) 05. Public method 5.1 Python built-in functions
Python includes the following built-in functions:
Function description remarks len (item) calculates the number of elements in the container
Del (item) there are two ways to delete the variable del max (item) returns the maximum value of the elements in the container if it is a dictionary, only for key comparison min (item) returns the minimum value of elements in the container if it is a dictionary, only for key comparison cmp (item1, item2) compare two values,-1 less than / 0 equal / 1 greater than Python 3.x cancels the cmp function
Be careful
The string conforms to the following rules: "0"
< "A" < "a" 5.2 切片描述Python 表达式结果支持的数据类型切片"0123456789"[::-2]"97531"字符串、列表、元组 切片 使用 索引值 来限定范围,从一个大的 字符串 中 切出 小的 字符串 列表 和 元组 都是 有序 的集合,都能够 通过索引值 获取到对应的数据 字典 是一个 无序 的集合,是使用 键值对 保存数据 5.3 运算符运算符Python 表达式结果描述支持的数据类型+[1, 2] + [3, 4][1, 2, 3, 4]合并字符串、列表、元组*["Hi!"] * 4['Hi!', 'Hi!', 'Hi!', 'Hi!']重复字符串、列表、元组in3 in (1, 2, 3)True元素是否存在字符串、列表、元组、字典not in4 not in (1, 2, 3)True元素是否不存在字符串、列表、元组、字典>> = = <
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.