Python Basics-The next day

Source: Internet
Author: User

The content of this article:

1. Lists (list)

2. Tuples (tuple)

3. Dictionary (dict)

4. Manipulation of strings



One, List

1. Defining the list

List_name = ["Element 1", "Element 2"]

A pair of brackets [] is the definition list;

if the element is a string, enclose it in double or single quotation marks;


2. Take the elements in the list

Show all the contents of a list

>>> city = ["Beijing", "Shanghai", "Guangzhou", "Nanjing"]>>> Print (city) [' Beijing ', ' Shanghai ', ' Guangzhou ', ' Nanjing ']


Take a single element in a list

>>> city = ["Beijing", "Shanghai", "Guangzhou", "Nanjing"]>>> print (city[0]) beijing>>> Print (city[3]) nanjing>>> print (city[-1]) Nanjing #-1 represents the last element of the list

Above is the subscript from the list of elements, the subscript starts from zero.


Add a small content, and take the element through a For loop:

>>> city = ["Beijing", "Shanghai", "Guangzhou", "Nanjing"]>>>-Place_name in City:print _NAME)-----The following is what is displayed-----beijingshanghaiguangzhounanjing


3. Slicing

>>> city = ["Beijing",  "Shanghai",  "Guangzhou",  "Nanjing"]>>>  print (City[0:2]) [' Beijing ',  ' Shanghai ']  #  shows all elements from subscript 0 to 2, but does not include the contents of subscript 2. >>> print (city[-3:-1]) [' Shanghai ',  ' Guangzhou ']  #  note that the order from the list is removed from left to right. >>> print (City[:2]) [' Beijing ',  ' Shanghai ']  #  if the start subscript is 0, you can omit to write. >>> print (city[1:]) [' Shanghai ',  ' Guangzhou ']  #  If the end subscript is-1, you can also omit to write. >>> print (city[:]) [' Beijing ',  ' Shanghai ',  ' Guangzhou ',  ' Nanjing ']#  When the start subscript and end subscript are omitted, it represents all the elements in the list >>>city = ["Beijing",  "Shanghai",  "Guangzhou",  " Nanjing ", " Wuhan "]>>> print (City[0:-1:2])   #[start subscript, end subscript, step [' Beijing ',  ' Guangzhou ']   #注意, the last Wuhan not shown, is Gu Tou regardless of the tail of the >>> print (City[::2]) [' Beijing ',  ' Guangzhou ',   ' Wuhan ']   #省略了开头和结尾, Wuhan is displayed.


4. Adding elements

Append:

>>> city = ["Beijing", "Shanghai", "Guangzhou", "Nanjing"]>>> city.append ("Wuhan") >>> print (city) [' Beijing ', ' Shanghai ', ' Guangzhou ', ' Nanjing ', ' Wuhan ']# add content in a way that is appended, so the new additions are in the last side of the list


Insert:

>>> city = ["Beijing", "Shanghai", "Guangzhou", "Nanjing"]>>> City.insert (1, "Wuhan") >>> Print (city) [' Beijing ', ' Wuhan ', ' Shanghai ', ' Guangzhou ', ' Nanjing ']# inserts the new content at the specified subscript



5. Change the contents of the list

>>> city = ["Beijing", "Shanghai", "Guangzhou", "Nanjing"]>>> city[3] = "Wuhan" >>> print (city ) [' Beijing ', ' Shanghai ', ' Guangzhou ', ' Wuhan ']


6. Delete the contents of the list

Delete Using Del

>>> city = ["Beijing", "Shanghai", "Guangzhou", "Nanjing"]>>> del city[0]>>> print (city) [' Wuhan ', ' Shanghai ', ' Guangzhou ', ' Nanjing ']>>> del City #删除整个列表


Remove with Remove

>>> city = ["Beijing", "Shanghai", "Guangzhou", "Nanjing"]>>> City.remove ("Shanghai") >>> Print (city) [' Beijing ', ' Wuhan ', ' Guangzhou ', ' Nanjing ']


7. Find the elements in the list

Use index to find unique elements

>>> city = ["Beijing", "Shanghai", "Guangzhou", "Nanjing"]>>> Print (City.index ("Shanghai")) 1 # The index of the element is displayed


Use Count to find the number of identical elements

>>> city = ["Beijing", "Shanghai", "Guangzhou", "Beijing"]>>> Print (City.count ("Beijing")) 2 # It shows how many Beijing this element is in total.


8. Empty the elements in the list

>>> city = ["Beijing", "Shanghai", "Guangzhou", "Nanjing"]>>> city.clear () >>> Print []


9. Merging lists

>>> city1 = ["Beijing", "Shanghai"]>>> city2 = ["Guangzhou", "Nanjing"]>>> City1.extend ( City2) >>> print (city1, city2) [' Beijing ', ' Shanghai ', ' Guangzhou ', ' Nanjing ' [' Guangzhou ', ' Nanjing '] # Note that City2 list is still here!



Two, tuple (tuple)

1. What is a tuple

tuples are in fact the same as the list, but also save a group of numbers, but once it is created, it can no longer be modified, can only slice and query, which means it only has 2 methods, one is Count , one is index.


2. Definition of a tuple

Tuple_name = ("element 1", "Element 2")


3. Taking elements from a tuple

>>> City = ("Beijing", "Shanghai", "Guangzhou", "Nanjing") >>> print (' Beijing ', ' Shanghai ', ' Guangzhou ', ' Nanjing ') >>> print (city[0]) beijing>>> print (City[0:2]) (' Beijing ', ' Shanghai ') # Shards and lists are the same!


4. Finding elements in tuples

>>> City = ("Beijing", "Shanghai", "Guangzhou", "Nanjing") >>> Print (City.index ("Shanghai")) 1 # The index of the element is displayed >>> city = ("Beijing", "Shanghai", "Guangzhou", "Beijing") >>> print (City.count ("Beijing") ) 2 # shows the number of Beijing this element in total



Three, dictionary (dict)

1. Introduction Dictionary

Dictionary a Key-value data type, using the same dictionary as we used to go to school, check the details of the corresponding page by strokes and letters.


2. Definition of a dictionary

>>> dict_name = {"Key1": "Value1", "Key2": "Value2",>>>}

the key in the dictionary is unique, which also means that the dictionary is inherently de-re-functional;

The dictionary does not have subscript, look up dictionary content is through key to find;

Dictionaries are unordered, and each time the dictionary content is displayed, the order of the contents is different;


3. Find content in a dictionary

>>> City = {"Beijing": "Haidianqu", "Shanghai": "Pudongxinqu", "Guangdong": "Guangzhou", ;>>}>>> Print (city["Beijing"]) haidianqu>>> print (City.get ("Beijing")) haidianqu>> > Print (City.get ("Hubei")) None # when unsure if the key exists, you can use this method if you don't have the key and return none without an error >>>


4. Modify and Add content

>>> City = {"Beijing": "Haidianqu", "Shanghai": "Pudongxinqu", "Guangdong": "Guangzhou", ;>>}>>> city["Beijing"] = "Chaoyangqu" # when the key is modified >>> print (city) {' Shanghai ': ' Pudongxinqu ', ' Guangdong ': ' Guangzhou ', ' Beijing ': ' Chaoyangqu '}>>> city[' hubei ' = ' Wuhan ' # Add content >>> PR when there is no key Int (city) {' Shanghai ': ' Pudongxinqu ', ' Beijing ': ' Chaoyangqu ', ' Hubei ': ' Wuhan ', ' Guangdong ': ' Guangzhou '}


5. Delete

>>> City = {"Beijing": "Haidianqu", "Shanghai": "Pudongxinqu", "Guangdong": "Guangzhou", ;>>}>>> del city["Beijing"] # Delete the specified key >>> print (city) {' Guangdong ': ' Guangzhou ', ' Shanghai ': ' Pudongxinqu '}>>> city.pop ("Shanghai") # Delete the specified key >>> print (city) {' Guangdong ': ' Guangzhou '}


6. Determine if key exists

>>> City = {"Beijing": "Haidianqu", "Shanghai": "Pudongxinqu", "Guangdong": "Guangzhou", ;>>}>>> Print ("Beijing" in the city) # Specifies that the key exists when it returns True, and returns false when it does not exist. True


7. Merging dictionaries

>>> city1 = {"Beijing": "Haidianqu", "Shanghai": "Pudongxinqu",>>>}>>> city2 = {"Beijing": "Chaoyangqu", "Guangdong": "Guangzhou",>>>}>>> city1.update (city2) >>&G T Print (city1) {' Shanghai ': ' Pudongxinqu ', ' Beijing ': ' Chaoyangqu ', ' Guangdong ': ' Guangzhou '}# two dictionaries have the same key, but value is different, The combined value is a different key in the value# two dictionary in City2, which is directly the contents of the merged dictionary.


8. Using in the For loop

>>> City = {"Beijing": "Haidianqu", "Shanghai": "Pudongxinqu", "Guangdong": "Guangzhou", ;>>}>>> for Place_name in city:>>> print (place_name) Guangdongbeijingshanghai # Show only key Oh >&G T;> for Place_name in city:>>> print (Place_name, city[place_name]) Guangdong guangzhoubeijing Haidianqushan Ghai Pudongxinqu # This is how key and value are displayed.



Iv. manipulation of strings

>>> Print ("Checklist". Center (10, "+")) ++++ List ++++ # only 10 strings are displayed, specifying the contents if there are No 10 strings, use + to complement each other at both ends


>>> print ("--\t--". Expandtabs (tabsize=5))----# tab equals 5 spaces


>>> print ("Abcdefghijk". Find ("D")) 3 # Here is the subscript, oh, is not an instant thought of the string can also do slices. >>> print ("Abcdefghijk" ["Abcdefghijk". Find ("D"): 7]) DEFG # is still Gu Tou regardless of the tail


>>> print ("Abc{d}e{f}". Format (d= "Y", f= "Z") Abcyez # content substitution


>>> Print ("1". IsDigit ()) true>>> print ("a". IsDigit ()) False # judgment is not an integer


>>> print ("AbcD". Isalpha ()) true>>> print ("Abcd1". Isalpha ()) False # Determines if there are only letters in the content


>>> print ("ABCDEFG". Islower ()) True # determines whether the content is not only lowercase letters >>> print ("ABCD". Isupper ()) True # Judge whether the English in the content is uppercase or not


>>> print ("#". Join (["A", "B", "C"]) A#b#c # Converts the list to a string, separated by the specified delimiter


>>> print ("ABCD". Lower ()) ABCD # Uppercase to lowercase >>> print ("ABCD". Upper ()) ABCD # lowercase to uppercase


>>> print ("Bcadeafgh". Split ("a")) [' BC ', ' de ', ' FGH '] # Specify delimiter to convert content to list

This article from "12031302" blog, declined reprint!

Python Basics-The next day

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.