Day6--python Data types

Source: Internet
Author: User

   e) list with [] representation      in Python, the most basic data structure is sequence (sequence). Each element in the sequence is assigned an ordinal-that is, the position of the element, also known as an index. The first index is 0, the second one is 1, and so on. The last element in the sequence is marked as-1, the penultimate element is-2, and so on.    lists are composed of elements arranged in a particular order of sequences, such as strings, numbers, dictionaries, and so on, which can have many elements.     python contains 6 of built-in sequences, including lists, tuples, strings, Unicode strings, buffer objects, and Xrange objects. The main difference between a list and a tuple is that the list can be modified and tuples cannot.       All sequence types can perform certain operations. These actions include: index (Indexing), Shard (sliceing), add (adding), multiply (multiplying), and check whether an element belongs to a member of a sequence (membership). In addition, Python has built-in functions for calculating the length of a sequence, finding the largest and smallest elements.  STR1 = ' dsfjasdfalsdf ' Print (list (str1)) #每个元素都是字符print (Type (str1)) a = [' A ', ' B ', ' C ', 123]print (a) print (type (a)) #查看类型为list类型print (dir (a)) #查看a属性的方法   return results for:      method: [' Append ', ' count ', ' extend ', ' index ', ' Insert ', ' pop ', ' remove ', ' reverse ', ' sort '] append: Used to append a new Element (object) to the end of the list.     Syntax: "" "L.append (object)--Append object to End" "" Print (a) a.append (' Hello ') print (a)   return result to:  Index: Detects if the string contains substring str, and if the start (start) and stop (end) ranges are specified, the check is contained within the specified range, which, like the Python Find () method, onlyHowever, if STR does not report an exception in the string, look for the subscript position where the character is located.     Syntax: L.index (value, [Start, [stop]]), integer--return first index of value.    parameter: STR--Specify Search String                 start--Start index, default is 0.                 stop--end index, which defaults to the length of the string. Print (a) print (A.index (' abc '))   return result:    insert: Used to insert the specified object into the specified position of the list.     Syntax: L.insert (Index, object)--Insert object before index     a.insert (0, ' YJB ') # Insert Yjbprint (a) A.insert (3, ' adasdfdasf ') at 0 subscript print (a)   return result to: 

Pop: Used to remove an element from the list (the last element by default), and returns the value of the element. Syntax: L.pop ([index]), item--Remove and return item at index (default last). Print (a) print (A.pop ()) #删除末位list元素print (a) The returned result is:

Remove: Used to remove the first occurrence of a value in the list. Syntax: L.remove (value)--Remove first occurrence of value.print (a) a.remove (' abc ') print (a) returns the result:

Print (a) a.remove (' abc ') print (a) a.append (' abc ') A.append (' abc ') print (a) a.remove (' abc ') A.remove (' abc ') # If you want to delete multiple identical elements, you need to write multiple deletions print (a) to return the result as:

Sort: Used to sort the original list and, if specified, use the comparison function specified by the comparison function (you can define your own comparison function). Syntax: L.sort (Cmp=none, Key=none, Reverse=false)--Stable sort *in place*;p rint (a) A.sort () #正序排序print (a) returns the result:

Reverse: Used to reverse the elements in the list. List reverse order (descending) syntax: L.reverse ()--Reverse *in place*print (a) A.reverse () #反序排序print (a) returns the result:

List slices: strings, lists, and tuples conform to the "sequence" feature in Python, and we can use slices (slice) to access any part of them, as long as the variables conform to this feature. We can think of the sequence as a queue, we may need the first three bits, the next three bits, or the third bit after the four bits, or one after another, we use the slice operator to achieve the above requirements slicing operator in Python prototype is: [Start:stop:step] that is: [Start index: End index: Step value] Start index: As in other languages, starting at 0, the sequence is left-to-right, the index of the first value is 0, and the last is the-1 end index: The slice operator will fetch the index, not the value step value of the index: the default is one after the tangent, if 2, it means to take one operation, the step value is positive to take from left to right, if negative, it means to take right-to-left, the step value cannot be 0 print (a) print (a[3:]) print (A[1:5]) #下标从1打印到5, note that when slicing, take the last digit-1 print (a) Print (A[1:5:2]) #隔几个取, the default 1 return result is: E) tuple tuple (tuple) is the immutable list, but the tuple is still a little different from the list 1.Tuple definition of tuple unique and list definition The difference is [] become (), the other does not have any changes, the tuple can not increase and decrease the elements inside (not add or remove elements inside), it itself very few methods, only count and index two methods, the other list method is not available str1= ' ABCDEFG ' Print (tuple (str1)) print (Type (tuple (STR1))) Returns the result:

2.Tuple single element Note: When a tuple represents a single element, the element is followed by a comma, otherwise the Python parser does not recognize the tuple type m= (' ABCD ') print (type (m)) n= (' abc ',) x= (123,) Print (Type (n)) printing (type (x)) Prints the result:

3.Tuple method: x= (123,) #tuple的方法print (dir (x)) Count: Counts the number of an element tu1= (' A ', ' B ', ' C ', ' a ', ' d ', ' a ', ' C ') print (Tu1.count (' a ')) The returned result is:

Indext: Returns the subscript of an element tu1= (' A ', ' B ', ' C ', ' a ', ' d ', ' a ', ' C ') print (Tu1.index (' d ')) prints the result:

Print (Tu1.index (' h ')) If an element does not exist, a direct error E) The dictionary is in the form of Key:value, the dictionary is another mutable container model, and each key value (key=>value) of any type of object dictionary can be stored Number (:) split, each pair is separated by a comma (,), and the entire dictionary is included in curly braces {}, the dictionary is assigned in three ways: 1. Dictionary Assignment method one: k = {' name ': ' YJB ', ' age ': ' Sex ': ' Man '}print (k) Print (type (k)) The return result is:

2. Dictionary assignment Method Two: #list (' ABCDEFG ') This is the list, tuple (' hijkml ') This is a tuple form, the dictionary can also be represented directly with dict K1 = dict (a=1,b=2,c=3) print (K1) print (Type (k1) The results are printed as:

3. Dictionary assignment Method Three (this method is not commonly used): The list is a tuple of the way d = dict ([' Name ', ' YJB '), (' age ')]) #这里面是一个列表, the outside is a dict function, inside is a list, the list is two tuples, print (d) The printed result is:

Dictionary Common methods: Print (dir (d)) clear: Clear the dictionary elements, the less common print (k1) k1.clear () printing (k1) Prints the result:

Get: Gets the key value of Vlue print (k.get (' name ')) print (K.get (' age ')) print (K.get (' ab ')) #如果里面没有的话会返回一个空值 printing results as:

SetDefault: Same as get to get the key value, when going to get the value, if there is a value to get its own value, if key does not have a value you can set (increase) a default value print (K.setdefault (' name ')) print ( K.setdefault (' age ')) print (K.setdefault (' ab ')) print (K.setdefault (' ab ', ' @@@ ')) print (K.setdefault (' abc ', ' 123 ')) Printing results are:

Keys: List all key values print (k) print (K.keys ()) Prints the result:

Iterkeys: Associated with keys, this is an object that will be followed by print (K.iterkeys ()) Printing results:

Values: Print out the value of key only print (K.values ()) Prints the result:

Iteritems: What is an object, then how to get it or get it? When you use the time one by one to take out the time will be displayed, do not take the object, take it once, will use the For loop. If the light prints out K.iteritems (), Print (K.iteritems ()) for k,v in K.iteritems ():p rint (k,v) results in:

Print (K.iteritems ()) #这是一个对象, it is recommended to use this, take once, if you want to get all the key values, if all the key values are taken out of the memory, so take one time with print (K.items ()) # After this is a list, each small element in the list is a tuple for x, and y in K.iteritems ():p rint (x, y) prints the result:

Pop: Delete the specified key value (cannot place value value, otherwise it will error, can only write key) print (k) k.pop (' name ') print (k) Prints the result:

Fromkeys: Get key# from a list to have a need, the value of L as M of the dictionary L = [' A ', ' B ', ' C ', ' d ']m = {} #n =m.fromkeys (l,123) #赋值所有的一个默认值为123n =dict.fromkeys (l,124) #上面也可以这么写也是成立的print (n) Prints the result:

Zip:zip is a culvert that merges two lists into a dictionary (by chance), #如果有两个字典的话, treats L1 as key, L2 as VALUEH1 = [' A ', ' B ', ' C ', ' d ']g2 = [1,2,3,4]dict_test = Zip (h1,g2) print (dict_test) results are:

Update: Merge Dictionary # If there are two dictionaries, take L1 as key, take L2 as VALUEH1 = [' A ', ' B ', ' C ', ' d ']g2 = [1,2,3,4]k = {' name ': ' YJB ', ' Age ': ' "Sex ': ' Man '} Dict_test = dict (Zip (h1,g2)) print (dict_test) print (k) #把上面第一个字典增加到第二个字典里面去, merge, overlay two dictionaries dict_test.update (k) Print ( dict_test) Prints the result as:

Soft: Sorting dictionaries

Ctrl-Click to see how this number is written #对字典进行排序soft, the following example is the sort by value mm = Dict (a=1,b=10,c=3,d=9) print (mm) print sorted (Mm.iteritems (), Key = Lambda D:d[1],reverse = True) #lambda是一个匿名涵数, D is a parameter print sorted (Mm.iteritems (), key = lambda D:d[1],reverse = False) Printing results are:

Day6--python 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.