Python tuples, lists, dictionaries, and files

Source: Internet
Author: User

PythonThe Data Types of tuples, lists, and dictionaries are very Python (there python isAdjective. These structures are optimized enough, so if they are used well, they will be of great benefit in some areas.

Tuples

 In my opinion, just like the Java array, the tuples in Python have the following features:

    • An ordered set of any object. This article does not cover the same type of array;
    • Read by offset;
    • Once generated, it cannot be changed;
    • Fixed Length, supporting nesting

For example:

Python Code
  1. >>> (0, 'hahaha', (4j, 'y '))
  2. (0, 'hahaha', (4j, 'y '))
  3. >>> T = (1, 3, 'B ')
  4. >>> T [2]
  5. 'B'
  6. >>> T [3]
  7. Traceback (most recent call last ):
  8. File"#41> ", line 1, in <module> </module>
  9. T [3]
  10. Indexerror:Tuple IndexOutRange
  11. >>> T [-1]
  12. 'B'
  13. >>> T [0:-1]
  14. (1, 3)
  15. >>> T * 2
  16. (1, 3, 'B', 1, 3, 'B ')
  17. >>>ForXInT:
  18. PrintX,
  19. 1 3 B
  20. >>> 'B'InT
  21. True
  22. >>> Q = T + (3, 'abc '))
  23. >>> Q
  24. (1, 3, 'B', 3, 'abc ')
  25. >>>ForXIn(2, (3, 'A ')):
  26. PrintX
  27. 2
  28. (3, 'A ')
  29. >>>Len(Q)
  30. 5
  31. >>>Len(2, (3, 'abc ')))
  32. 2
  33. >>> (1, 2, 3) [1]
  34. 2
  35. >>> Q [1] = 'D'
  36. Traceback (most recent call last ):
  37. File"#57> ", line 1, in <module> </module>
  38. Q [1] = 'D'
  39. Typeerror:'Tuple'ObjectDoesNotSupport item assignment
  40. >>> A = ('B', 'C', q)
  41. >>> 1InA
  42. False
  43. >>> QInA
  44. True
  45. >>>
  46. ('B', 'C', (1, 3, 'B', 3, 'abc '))
  47. >>> Q = 'D'
  48. >>>
  49. ('B', 'C', (1, 3, 'B', 3, 'abc '))

The above example is enough to illustrate the majority. The most important thing when using tuples is "Once generated, it will not be changed ".

List

The list is likeCollection, which has more features than tuples and is more flexible.Character is summarized as follows:

    • An ordered set of any object;
    • You can use offset access. Note that the elements in the list are variable, which is different from the tuples;
    • Variable Length, supports nesting;
    • There are also some object reference mechanisms similar to Java

These features make the list widely used in practical applications. The following are some examples.

1) The first is basic usage.

Python code
  1. >>> L = ['A', 'B', 'C']
  2. >>>Len(L)
  3. 3
  4. >>> L + ['D']
  5. ['A', 'B', 'C', 'D']
  6. >>> L * 2
  7. ['A', 'B', 'C', 'A', 'B', 'B']
  8. >>>ForXInL:
  9. PrintX,
  10. A B C

2) index and partition, assign values (assign values to a single element, assign values to a partition)

Python code
  1. >>> L = ['abc ','Def', 'Ghi', 123]
  2. >>> L [2]
  3. 'Ghi'
  4. >>> L [-3]
  5. 'Def'
  6. >>> L [: 3]
  7. ['Abc ','Def', 'Ghi']
  8. >>> L [1] = 'hahaha'
  9. >>> L
  10. ['Abc', 'hahaha', 'ghi', 123]
  11. >>> L [1:] = ['apple', 'Banana ']
  12. >>> L
  13. ['Abc', 'apple', 'bana']
  14. >>> L [2] = [123,345,456]
  15. >>> L
  16. ['Abc', 'apple ', [123,345,456]
  17. >>> L [1:] = [1, 123,234,345,456,567]
  18. >>> L
  19. ['AB', 123,234,345,456,567]

 

3) add, sort, and delete operations

Python code
  1. >>> L = ['abc ','Def', 'Ghi', 123]
  2. >>> L.Append(456)
  3. >>> L
  4. ['Abc ','Def', 'Ghi', 123,456]
  5. >>> L. Sort ()
  6. >>> L
  7. [123,456, 'abc ','Def', 'Ghi']
  8. >>>DelL [0]
  9. >>> L
  10. [456, 'abc ','Def', 'Ghi']
  11. >>>DelL [2:]
  12. >>> L
  13. [456, 'abc']

4) some interesting usage (from the Forum ID-Coffee dancer)

Remove the spaces at the beginning and end of each element in the list:

Python code
    1. >>> Freshfruit = ['bana', 'login', 'passion fruit']
    2. >>> [Str. Strip ()For Str InFreshfruit]
    3. ['Bana', 'loganberry ', 'passion fruit']

Multiply the element greater than 3 in the list by 2:

Python code
    1. >>> VEC = [2, 4, 6]
    2. >>> [2 * xForXInVECIfX> 3]
    3. [8, 12]

Multiply each element in List 1 and each element in List 2:

Python code
    1. >> lst1 = [2, 4, 6]
    2. >> lst2 = [4, 3, -9]
    3. >>> [x * Y for x in lst1 for Y in lst2]
    4. [8, 6,-18, 16, 12,-36, 24, 18, -54]

Obtain the square value of [0-10:

Python code
    1. [X ** 2ForXIn Range(10)]

Dictionary

The dictionary in python is like a hashmap in Java. It exists and operates as a key-value pair. Its features are as follows:

    • Key-based access, rather than offset;
    • Key-value pairs are unordered;
    • Keys and values can be arbitrary objects;
    • Variable Length, any nesting;
    • In the dictionary, sequence operations are not allowed. Although the dictionary is similar to the list in some aspects, do not set the list on the dictionary.

1) basic operations

Python code
  1. >>> Table = {'abc': 1 ,'Def': 2, 'ghi': 3}
  2. >>> Table ['abc']
  3. 1
  4. >>>Len(Table)
  5. 3
  6. >>> Table.Keys()
  7. ['Abc', 'ghi ','Def']
  8. >>> Table.Values()
  9. [1, 3, 2]
  10. >>> Table.Has_key('Def')
  11. True
  12. >>> Table.Items()
  13. [('Abc', 1), ('ghi', 3 ),('Def', 2)]

2) modify, delete, and add

Python code
  1. >>> Table = {'abc': 1 ,'Def': 2, 'ghi': 3}
  2. >>> Table ['ghi'] = ('G', 'h', 'I ')
  3. >>> Table
  4. {'Abc': 1, 'ghi': ('G', 'h', 'I '),'Def': 2}
  5. >>>DelTable ['abc']
  6. >>> Table
  7. {'Ghi': ('G', 'h', 'I '),'Def': 2}
  8. >>> Table ['xyz'] = ['x', 'y', 'z']
  9. >>> Table
  10. {'Xyz': ['x', 'y', 'z'], 'ghi': ('G', 'h', 'I '),'Def': 2}

Here, you need to define a new key-value pair for the dictionary extension. For the list, you can only use the append method or multipart assignment.

3) dictionary Traversal

Python code
  1. >>> Table = {'abc': 1 ,'Def': 2, 'ghi': 3}
  2. >>>ForKeyInTable.Keys():
  3. PrintKey, '\ t', table [Key]
  4. ABC 1
  5. Ghi 3
  6. Def2

File

Compared with the file class in Java, the file class in Python must be narrower.

1) file writing

Python code
    1. >>> Myfile =Open('Myfile', 'w ')
    2. >>> Myfile.Write('Hello world \ n ')
    3. >>> Myfile.Close()

A python open statement opens a file (a new file is automatically created when the specified file does not exist ). The first parameter of open is the file name, and the second parameter is the operation mode. The so-called operation mode is what you use to open a file and read the file, or write (of course, the operation mode is not only read and write ). There is another thing to remember after the operation.

2) File Reading

Python code
    1. >>> Myfile =Open('Myfile', 'R ')
    2. >>> Myfile.ReadlineReadline()
    3. 'Hello world \ N'

It is very simple. In this case, the two sentences are nested with a long string of Java streams. Of course, it makes sense to do that in Java.

Okay, I learned a lot. To be honest, there are really few Python cores, and it's very easy. It's hard to know how to use python at the same time.

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.