[Python] study notes 4-tuples

What is a tuple?

A tuple is a sequence, just like a list. The difference between tuples and lists is that, unlike lists (mutable), tuples cannot be changed (immutable).
Tuples use brackets (), and lists use square brackets [].

1. Initialize tuples and assign values

#两种方法都可以初始化
emptyTuple=()
emptyTuple1=tuple()

#两种方法都可以赋值
emptyTuple=(1,2,3,4)
emptyTuple1=1,2,3,4

print(emptyTuple)
print(emptyTuple1)

result:
Insert picture description here

It is important to remember

If you want to create a tuple that contains only one value, you need to add a comma after the item.

#只有一个值的话后面要加逗号
tup=('a',)
tup1='a',

#如果没有逗号,那它是一个string不是一个元组了
notTuple=('a')

print(tup)
print(tup1)
print(notTuple)

Result:
Insert picture description here
2. Visit value

tun=(2,3,4,5)
print(tun[0])#索引正向从0开始
print(tun[-4])#索引负向从最后一个-1开始倒数

Results:
Insert picture description here
3. Split tuples

tun=(2,3,4,5)
print(tun[0:2])
print(tun[:3])
print(tun[-3:-1])

Result:
Insert picture description here
4. The tuple cannot be changed

tun=(2,3,4,5)
tun[0]='fish'

result:
Insert picture description here

Even if the tuple is immutable, a part of the existing tuple can be used to create a new tuple

tun=(2,3,4,5)
tun1=(6,7,8,9)
tunall=tun+tun1
print(tunall)

Results:
Insert picture description here
5. Tuple method

animals=('pig','pig','cat',1)

#返回索引
print('pig first index: ',animals.index('pig'))
print('cat first index: ',animals.index('cat'))

#计数
print(animals.count('pig'))

result:
Insert picture description here

6. Iterate over tuples

animals=('pig','pig','cat',1)

for item in animals:
    print(item)

for item in ('a','b','c'):
    print(item)

Results:
Insert picture description here
7. Tuple unpacking Tuples
are very useful for sequence unpacking

x,y=(7,10)
print(x)
print(y)

print("Value of x is {},the value of y is {}".format(x,y))

Result:
Insert picture description here
8. Enumeration The
enumeration function returns a tuple containing the count of each iteration (starting from the default of 0) and the value obtained by the iteration sequence

friends = ('Steve', 'Rachel', 'Michael', 'Monica')
for index, friend in enumerate(friends):
    print(index,friend)
    print(index)
    print(friend)


for index in enumerate(friends):
    print(index)

result:
Insert picture description here

Advantages of tuples over lists

Lists and tuples are standard Python data types used to store values ​​in sequences. Tuples are immutable, while lists are mutable.

Here are some other advantages of tuple lists:

**Groups are faster than lists. **If you are going to define a set of constant values, then all you will do is iterate over it, using tuples instead of lists. The performance difference can be measured in part using the timeit library, which allows you to time your Python code. The following code runs the code 1 million times for each method and outputs the total time spent (in seconds).

import timeit 
print('Tuple time: ', timeit.timeit('x=(1,2,3,4,5,6,7,8,9,10,11,12)', number=1000000))
print('List time: ', timeit.timeit('x=[1,2,3,4,5,6,7,8,9,10,11,12]', number=1000000))

Result:
Insert picture description here
Tuples can be used as dictionary keys : Some tuples can be used as dictionary keys (especially tuples containing immutable values, such as strings, numbers, and other tuples). Lists can never be used as dictionary keys, because lists are not immutable.

bigramsTupleDict = {
    
    ('this', 'is'): 23,
                    ('is', 'a'): 12,
                    ('a', 'sentence'): 2}

print(bigramsTupleDict)

Result:
Insert picture description here
but the list does not work

bigramsListDict = {
    
    ['this', 'is']: 23,
                   ['is', 'a']: 12,
                   ['a', 'sentence']: 2}

print(bigramsListDict)

Result:
Insert picture description here
Tuples can be values ​​in the collection

graphicDesigner = {
    
    ('this', 'is'),
                   ('is', 'a'),
                   ('a', 'sentence')}
print(graphicDesigner)

Result: The
Insert picture description here
list cannot be a value in the collection:

graphicDesigner = {
    
    ['this', 'is'],
                   ['is', 'a'],
                   ['a', 'sentence']}
print(graphicDesigner)

result:
Insert picture description here

Guess you like

Origin blog.csdn.net/Shadownow/article/details/105818489