Learn Python's notes today

zhaozj2021-02-16  72

Tuple introduction

Tuple is a non-variable List. Once the TUPLE is established, it cannot be changed in any way.

Define tuple

>>> t = ("a", "b", "mpilgrim", "z", "example") >>> t ('a', 'b', 'mpilgrim', 'Z', 'Example' >>> T [0] 'A' >>> T [1] 'Example' >>> T [1: 3] ('b', 'mpilgrim')

The definition of tuple is the same as the list, except that the entire element set is enclosed in parentheses rather than square brackets. Tuple's element is sorted in the defined order. TUPLE's index appearance starts from 0, so the first element of a non-empty Tuple is always T [0]. The negative index is the same as the tail of the TUPLE starts. Split is also working like List. Please note that when you sharpen a LIST, you will get a new list; when you sharpen a TUPLE, you get a new Tuple.

Tuple has no way

>>> T ('A', 'B', 'MPilgrim', 'Z', 'Example') >>> T.Append ("New") Traceback (Innermost Last): File "", LINE 1, IN? AttributeError: 'Tuple' Object Has No Attribute 'Append' >>> T.Remove ("Z") Traceback (InnerMost Last): File "", LINE 1, IN? AttributeError: ' tuple 'object has no attribute' remove '>>> t.index ( "example") Traceback (innermost last):? File "", line 1, in AttributeError:' tuple 'object has no attribute' index '>>> "z" in t 1

You cannot add an element to tuple. TUPLE does not have an Append or Extend method. You can't delete elements from tuple. TUPLE has a REMOVE or POP method. You can't find elements in tuple. TUPLE does not have an Index method. However, you can use IN to see if an element exists in tuple.

So what is TUPLE is there?

TUPLE is faster than the LIST operation. If you define a constant set of values, and the only thing to do with it is constantly traversing it, use tuple instead of List. This makes the code more secure if you don't need to modify data. Using TUPLE instead of list, if you have an implicit ASSERT statement, this data is constant. If you want to overwrite it, you need special ideas (and a special function). [5] Remember that I said that Dictionary Key can be Integer, String, and "How many other types"? TUPLE is one of those types. Tuple can be used as KEY in Dictionary, but List can't. [6] Tuple can be used in String, we will see it very quickly. Tuple can be converted to LIST, which is in turn. The built-in Tuple function receives a list and returns a TUPLE with the same elements. The List function receives a TUPLE to return a list. From the effect, Tuple frozen a list, and List is thawed a tuple.

转载请注明原文地址:https://www.9cbs.com/read-16059.html

New Post(0)