Tuple--python

Source: Internet
Author: User

Tuples are a sequence of values, can be of any type, can be indexed by subscript, but tuples are immutable

To create a tuple:

t= (' A ', ' B ', ' C ')

T= ' A ',----only one element needs to be appended with a comma

Tuple ()---parameter can be a sequence (string, list, tuple)

T=tuple (' hello ')----results (' h ', ' e ', ' l ', ' l ', ' o ')

Get element:

T[0] T[1:3]

To modify a tuple:

T=tuple (' Hello ')
t= (' H ',) +t[1:]---can replace an entire tuple cannot modify elements of a tuple

Tuple Exchange Assignment:

A,b=b,a

Tuples as return values:

def min_max (t):
return Max (t), min (t)
T= (1,3,2,5)
Print (Min_max (t))

Variable-length parameter tuples---functions can receive an indefinite number of parameters:

Collect----

def printall (*args):---parameter names that begin with a * collect all parameters on a single tuple
Print (args)
Printall (1,2.0, ' H ')

Disperse---

T= (7,3)
Print (Divmod (*t))-----Divmod () returns a tuple (quotient, remainder); *t groups The tuples

List and tuples, dictionaries, and tuples:

ZIP---sequence variable tuple table

s= ' abc '
t=[0,1,2]
L=list (Zip (s,t))-----[(' A ', 0), (' B ', 1), (' C ', 2)]
D=dict (Zip (s,t))----{' A ': 0, ' B ': 1, ' C ': 2}

Dictionary conversion to tuples:

D={' A ': 0, ' B ': 1, ' C ': 2}
For Key,val in D.items ():
Print (Key,val)

Results:

A 0
B 1
C 2

Compare tuples:

The relational operator is available for tuples and other sequences, and Python starts from the first element of each sequence, and if equal compares the next element until a different element is found

x= (1,2,4)
Y= (a)
Print (x>y)----true
Print (x<y)----false

Sorting---sort () for list

T.sort (reverse=true)---descending order

Tuple--python

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.