List of Python basic data types

Source: Internet
Author: User
Tags extend

Lists: Definitions and attributes

List Definition and creation:

Definition: [,] within a comma-delimited, by index, storing various data types, generally no restrictions, each position represents an element

  

Range_create = List (range (0, 10))
Print (range_create)
>>:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

str = ' Yanxiatingyu '
str_create = List (str)
Print (str_create)
>>:[' y ', ' a ', ' n ', ' x ', ' I ', ' a ', ' t ', ' I ', ' n ', ' g ', ' Y ', ' u ']

Iter_create=[lis for LIS in range (0,10)]
Print (iter_create)
>>:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Characteristics:
1. Multiple values can be stored
2. Define list elements in left-to-right order, order access from 0, ordered
3. Can modify the value of the specified index position, variable

#取值
#索引 value is basically the same as a string operation
Name= ' Yanxiatingyu '
Name_list=list (name)
Print (Name_list[0])
>>:y
Print (name_list[:]) #不设限
Print (Name_list[::2]) #正向步长
Print (name_list[::-1]) #取反

#追加
Name_list.append (' new_element ')


#在指定位置添加元素, if the specified subscript does not exist, it is added at the end
#插入
Name_list.insert ()
name_list= (' Yan Xia Ting Yu '). Split ()
Print (name_list)
Name_list.insert (3, ' Hello Insert ')
Print (name_list)
[' Yan ', ' xia ', ' ting ', ' Yu ']
[' Yan ', ' xia ', ' ting ', ' hello Insert ', ' Yu ']



Way One
Name_list.remove (' new_element ')

Way Two
Name_list.append (' new_element ')
Del name_list[name_list.index (' New_element ')]
Print (name_list)

List.pop () Delete the last element

List.pop (n) specifies the subscript, deleting the specified element, and if deleting a nonexistent element will cause an error

List.remove (XX) removes an element from the list, has multiple identical elements, deletes the first

Print (List.pop ()) has a return value

Print (List.remove ()) No return value

Del List[n] Delete the element corresponding to the specified subscript

Del list deletes the entire list and cannot be accessed after list is deleted

List.reverse () Reverses the list

List.sort () sort, default ascending

List.sort (reverse=true) descending order

Note: There are strings in list, numbers cannot be sorted, sorting is for the same type

Six, function of list operation

1. Len (list): Number of elements
2. Max (list): Returns the maximum value of the element
3, Min (list): Returns the minimum value of the list element
4. List (seq): Convert tuples to lists

5, Enumerate usage (print the corresponding subscript of the element)

While removing the label, the element



Length
Print (len (name_list))


' In vs not ' in operator contains and does not contain a relationship

If ' new_element ' in name_list:
Print (' presence of this element ')
If ' new_element ' not in Name_list:
Print (' This element does not exist ')

"Count statistics characters in list occurrences"
Print (Name_list.count (' statistics '))

"Find value, and return index"
Name_list.index (' a ') #
Returns the index at the first occurrence of the element if it exists, no error: Valueerror:element is not in list
Name_list.index (' A ', 0,5) #返回element where the first occurrence occurs within the specified slice

Third, view the values in the list

Print (list) traversal list

Equivalent to the For I in list:

Print I

Print (List[n]) uses the subscript index to access the values in the list, and you can also use square brackets to intercept the characters

Print (List.count (xx)) to see the number of elements in this list, if the element does not exist, then return 0

Print (List.index (xx)) Find the small label of this element, if there are multiple, return the first, if a non-existent element will be an error



"List and Iteration loops"
For I,item in Enumerate (name_list): #可迭代循环
Print (' name_list[%s]:%s '% (I,item))


#列表与字符串
Name= ' Yan Xia Ting Yu '
Name_list=name.split (")
Print (name_list)
>>:[' Yan ', ' xia ', ' ting ', ' Yu ']

Print (". Join (name_list)")
>>:yan Xia Ting Yu


 #列表 advanced Operations and efficiency issues 
Name_list = (' Yan Xia Ting Yu '). Split (')
List_zhang = ' Zhang Huan Huan '. Split (')
Name_l ist + = List_zhang
#说明: With the + sign connector This is less efficient,
# Create a new list and copy all the objects in the past,
# and append the elements to the existing list
# (especially when building a large list) is much better
Name_list.extend (List_zhang)
Print (name_list)





#排序
#用sort方法可以实现就地排序 (without creating a new object, The string is sorted by the first letter)
Name= ' Yanxiatingyu '
name_list=list (name)
Print (name_list)
Name_list.sort ()
Print ( name_list)
#[' Yan ', ' xia ', ' ting ', ' Yu ', ' Zhang ', ' Huan ', ' Huan ', ' Zhang ', ' Huan ', ' Huan ']
#[' y ', ' a ', ' n ', ' x ', ' I ' , ' a ', ' t ', ' I ', ' n ', ' g ', ' Y ', ' u ']
#[' A ', ' a ', ' g ', ' I ', ' I ', ' n ', ' n ', ' t ', ' u ', ' x ', ' y ', ' y ']
#sort有几个很好用的选项, a is a secondary sort key, and
# is a function that produces a value that can be used for sorting. If you can sort a set of strings by length
#使用sort sort does not return a new list

name_list=list (' Yanxiatingyu ')
Name_list.sort (key=len) #
Print (name_list)
>>:[' y ', ' a ', ' n ', ' x ', ' I ', ' a ', ' t ', ' I ', ' n ', ' g ', ' Y ', ' u ']
#是否进行降序排列:
# The following example is a row based on the first letter Sequential Operation
Name_list.sort (key= Lambda  x:x[0],reverse=true)
Print (name_list))

>>:[' y ', ' y ', ' x ', ' u ', ' t ', ' n ', ' n ', ' I ', ' I ', ' g ', ' a ', ' a ']

Two-point search and maintain ordered list (bisect)

The built-in bisect module implements two-point lookup and insert operations on sequential tables. Bisect.bisect can find out where the new element should be inserted to maintain the order of the meta-list, and Bisect.insort inserts the new element into that correct position.

Note: The functions of the Bisect module do not determine whether the original list is ordered, because it is expensive to do so, and so while they are used as unordered lists, there is no error, but may result in incorrect results. Based on this, it is recommended that you perform a sort operation on the original list before using the functions of the Bisect module.

#79685168 #原文: Managing list operations
#https://www.cnblogs.com/yanxiatingyu/p/9277019.html #关于bisect Module
#https://www.cnblogs.com/skydesign/archive/2011/09/02/2163592.html #关于bisect模块

Slices (index operators [] and Start:stop)

You can slice the sequence type (array, list, tuple, and so on), the element at the start index is included in the result of the slice, the element at the stop index is not included in the result, and the number of elements is stop-start. Start or stop can be omitted, at which point they are defaulted to the beginning and end of the sequence respectively.

Slice operation: can refer to my post, striing this piece


List of built-in sequence functions enumerate

The enumerate function can return a combination of sequences (key,value), which allows you to get the type of container you want.
As follows:
name = ' Yanxiatingyu '
name_list = List (name)
Name_dict= Dict ((key + 1, value) for key, value in enumerate (name_list))
Print (Type (name_dict), name_dict)
>>:<class ' Dict ' > {1: ' Y ', 2: ' A ', 3: ' N ', 4: ' X ', 5: ' I ', 6: ' A ', 7: ' t ', 8: ' I ', 9: ' N ', Ten: ' G ', one: ' Y ', 1 2: ' U '}

Six, function of list operation

1. Len (list): Number of elements
2. Max (list): Returns the maximum value of the element
3, Min (list): Returns the minimum value of the list element
4. List (seq): Convert tuples to lists

5, Enumerate usage (print the corresponding subscript of the element)

While removing the label, the element



#sorted () sort is to return a new list
#sort () is an in-place sort
Print (sorted (name_list))
[' A ', ' a ', ' g ', ' I ', ' I ', ' n ', ' n ', ' t ', ' u ', ' x ', ' y ', ' y ']

#sorted and set are used together to get a list of ordered, element-less duplicates
Print (sorted (' Yan Xia Ting Yu '))
Print (sorted (set (' Yan Xia Ting Yu ')))
# [', ', ', ' ', ' a ', ' a ', ' g ', ' I ', ' I ', ' n ', ' n ', ' t ', ' u ', ' x ', ' y ', ' y ']
# [', ' a ', ' g ', ' I ', ' n ', ' t ', ' u ', ' x ', ' Y ']
Print (Set (' Yan Xia Ting Yu '))
Print (Set (sorted (' Yan Xia Ting yu ')) #字典是无序的, so the following is also unordered, do not believe you can try to run a few more times
# {' I ', ' a ', ' X ', ' g ', ' ', ' n ', ' y ', ' t ', ' u '}
# {' I ', ' a ', ' g ', ' X ', ' ', ' n ', ' u ', ' t ', ' Y '}

Zip is used to "pair" the elements in multiple sequences (lists, tuples, and so on), resulting in a new tuple list, which can accept any number of sequences, and ultimately the number of tuples to be determined by the shortest sequence; the most common use of zip is to iterate over multiple sequences at the same time and use them together with enumerate As follows:

 name = ' Yan Xia ting yu ' 
name_list =name.split ()
Print (name_list)
girl= ' girl1 girl2 girl3 girl4 '
Girl_ List=girl.split ()
Print (girl_list)
Iter_zip=zip (girl_list,name_list)
Print (Type (iter_zip))
Print (' Iter_zip ')
for v,k in Iter_zip:
Print (v,k)

Print (' Enumerate (iter_zip) ')
-i,v in Enumerate (iter_ Zip): #这里无法输出?
Print ('%s%s '% (i+1,v))

Print (' Enumerate (Zip (girl_list,name_list)) ')
for I, (v,k) in Enumerate (Zip (girl_list,name_list)):
Print ('%s%s '% (i+1,v,k))

# [' Yan ', ' xia ', ' ting ', ' Yu ']
# [' Girl1 ', ' girl2 ', ' girl3 ', ' Girl4 ']
# <clas s ' Zip ';
# iter_zip
# girl1 Yan
# girl2 Xia
# girl3 Ting
# girl4 Yu
# Enumerate (iter_zip)
# Enumer Ate (Zip (girl_list,name_list))
# 1 Girl1 Yan
# 2 Girl2 Xia
# 3 Girl3 Ting
# 4 girl4 yu

  for "compressed" (Zi pped) sequence, zip also has a clever use of the sequence to extract (unzip, denoted by *)
. In fact, "convert a group of rows to a set of columns"
is as follows:

teacher=[(' Egon ', +), (' Lqz ', +), (' Wxx ', 20)]
Name,age=zip (*teacher)
Print (Type (name), name)
# <class ' tuple ' > (' Egon ', ' lqz ', ' wxx ')
Print (Type (age), age)
# <class ' tuple ' > (18, 16, 20)


teacher=[(' Egon ', +), (' Lqz ', 16)]
Name1,name2=zip (Teacher)
Print (Type (name1), name1)
# <class ' tuple ' > (' Egon ', 18),)
Print (Type (name2), name2)
# <class ' tuple ' > (' Lqz ', 16),)
name_list= (' Yan Xia Ting Yu '). Split ()
Print (name_list)
[' Yan ', ' xia ', ' ting ', ' Yu ']



"Data Decompression"
X,y,z,_=name_list
Print (_)
X,y,*_=name_list
Print (x)
Print (*_)
#Yu
#
Yan
#
Ting Yu


The #逆向排序 reversed () function is the iteration that returns the reverse access of the sequence seq. The parameter can be a list, a tuple, a string, and not change the original object.

print ([x for X in reversed ([1,2,5,4,-1])])
>>:[-1, 4, 5, 2, 1]










Head First Python Summary:
1, the list is an ordered collection of objects
2, is one object in another object? Use in to check

3, remove the object from the list
Remove: Takes an object value as a unique parameter. The Remove method removes the first occurrence of the specified data value from the list.

If the data value is found in the list, the object containing the value is removed from the list (and the size of the list is reduced by one). If the data value is not found in the list, an error occurs.

4. POPs an object from the list
Pop: Take an optional index value (indexof) as the parameter. The Pop method removes and returns an object from an existing list based on the index value of the object.

If you do not specify an index value when calling Pop, the last object in the list is deleted and returned. If an index value is specified, the object at that location is deleted and returned.

If the list is empty or a non-existent index value is specified when calling pop, an error is given.

5, expand list with object extend
Extend: Takes an object list as a unique parameter. The Extend method receives a second list, adding individual objects to the existing list. This method is useful if you want to combine two lists into a single list.

6, insert an object in the list insert/append
Insert: Takes an index value and an object as a parameter. The Insert method inserts an object in front of the specified index value in the existing list.

This allows you to insert an object at the beginning of an existing list, or at any point in the list. To insert an object at the end of the list, use append. Usage Num.insert (2, "abc")

7, how to copy a data structure? Do not copy the list using the assignment operator, you should use the Copy method.
Assignment actions point to the same data, and if you modify one list, the other changes, and if you want another variable to refer to an existing list, you can use the assignment action (=)
Copy:list2 = List1.copy (); If you want to make a copy of an object in an existing list, use the Copy method to initialize a new list with them

8, the use of the list slice "Start:stop:step" does not contain the STOP index value
When step is positive, from right to left, step is negative, from left to right













List of Python basic data types

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.