Get the App
SLTechnology News&Howtos  ›  Development  › 

The usage of tuples in Python basic data types

Shulou Source: shulou.com Published: 2022-06-03 00:19:15 09月23日 Update

This article shows you the use of tuples in Python basic data types, which is concise and easy to understand. I hope you can get something through the detailed introduction of this article.

1. The concept of tuple

Tuples in python are a collection of ordered elements. Unlike lists, tuples are immutable and cannot be modified once defined.

Remember that tuples are immutable

two。 Definition of tuple

You can initialize tuples directly using tuple () or ()

When you define a tuple of a single element, you need to add a comma after the single element, such as t = (1,)

3. Access to tuple t = (1) print (t [2]) # output 3

Tuple access is similar to a list, which can be accessed through an index

4. Tuple modification

Because tuples cannot be modified, there is no way to add, delete, modify and check tuples, which also reflects the immutability of tuples.

5. Named tuple from collections import namedtuplePoint = namedtuple ('Point', [' axiomachine']) point = Point (1,2) print (point.a) # output 1print (point.b) # output 2

You need to import a namedtuple class through the collection module before using it.

Build a tuple class: class name = namedtuple ('class name', [iterable object])

Initialize tuple instance

Access tuples (tuples are also accessed through dot syntax)

6. Bubbling sort lst = list ([1Jing 2 Jing 7 Jing 6 Jing 5 Ji 4]) print (lst) # output [1Bing 2 Jing 7 Jing 6 Jing 3 Jing 5 4] for i in range (len (lst)): # for j in range (len (lst)-I-1): if lst [j] > lst [juni1]: # make the element exchange position tmp = lst [j] lst [j] = lst [juni1] lst [juni1] = tmp print (lst) # output [1,2,3,4] 5, 6, 7]

Compare the two adjacent elements, put the large ones back, and finally the largest element should be at the end of the queue.

After each comparison, the next comparison will be reduced.

Bubbling sort has two layers of loops, the outer loop controls the number of comparisons, and the inner loop is used to compare the size of elements.

The above is the use of tuples in the Python basic data type. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Tags: Element output loop sort data type meta content single skill knowledge class name variable maximum ordered concise concise two between position Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Microsoft vpn MySQL MariaDB