07 tuple

Reprinted from Datawhale open source learning library

https://github.com/datawhalechina/team-learning-program/tree/master/PythonLanguage

Tuple

"Tuple" definition syntax is:(元素1, 元素2, ..., 元素n)

  • Parentheses tie all elements together
  • Comma separates each element one by one

1. Create and access a tuple

  • Python tuples are similar to lists. The difference is that tuples cannot be modified after they are created, similar to strings.
  • Use parentheses for tuples and square brackets for lists.
  • Tuples are similar to lists, and integers are used to index and slice them.

【example】

t1 = (1, 10.31, 'python')
t2 = 1, 10.31, 'python'
print(t1, type(t1))
# (1, 10.31, 'python') <class 'tuple'>

print(t2, type(t2))
# (1, 10.31, 'python') <class 'tuple'>

tuple1 = (1, 2, 3, 4, 5, 6, 7, 8)
print(tuple1[1])  # 2
print(tuple1[5:])  # (6, 7, 8)
print(tuple1[:5])  # (1, 2, 3, 4, 5)
tuple2 = tuple1[:]
print(tuple2)  # (1, 2, 3, 4, 5, 6, 7, 8)
  • To create a tuple, you can use parentheses () or nothing. For readability, it is recommended to use ().
  • When the tuple contains only one element, you need to add a comma after the element, otherwise the parentheses will be used as operators.

【example】

x = (1)
print(type(x))  # <class 'int'>
x = 2, 3, 4, 5
print(type(x))  # <class 'tuple'>
x = []
print(type(x))  # <class 'list'>
x = ()
print(type(x))  # <class 'tuple'>
x = (1,)
print(type(x))  # <class 'tuple'>

【example】

print(8 * (8))  # 64
print(8 * (8,))  # (8, 8, 8, 8, 8, 8, 8, 8)

[Example] Create a two-dimensional tuple.

x = (1, 10.31, 'python'), ('data', 11)
print(x)
# ((1, 10.31, 'python'), ('data', 11))

print(x[0])
# (1, 10.31, 'python')
print(x[0][0], x[0][1], x[0][2])
# 1 10.31 python

print(x[0][0:2])
# (1, 10.31)

2. Update and delete a tuple

【example】

week = ('Monday', 'Tuesday', 'Thursday', 'Friday')
week = week[:2] + ('Wednesday',) + week[2:]
print(week)  # ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday')

[Example] Tuples are immutable, so you cannot directly assign values ​​to the elements of the tuple, but as long as the elements in the tuple can be changed (mutable), then we can directly change its elements. Note that this is followed by assignment. The elements are different.

t1 = (1, 2, 3, [4, 5, 6])
print(t1)  # (1, 2, 3, [4, 5, 6])

t1[3][0] = 9
print(t1)  # (1, 2, 3, [9, 5, 6])

3. Operators related to tuples

  • Equal sign operator:==
  • Concatenation operator +
  • Repeat operator *
  • Membership operator in,not in

"Equal sign ==", it returns True only when the members and member positions are the same.

There are two ways to concatenate tuples, using "plus sign +" and "multiplication sign *". The former is spliced ​​at the end and the latter is copied and spliced.

【example】

t1 = (123, 456)
t2 = (456, 123)
t3 = (123, 456)

print(t1 == t2)  # False
print(t1 == t3)  # True

t4 = t1 + t2
print(t4)  # (123, 456, 456, 123)

t5 = t3 * 3
print(t5)  # (123, 456, 123, 456, 123, 456)

t3 *= 3
print(t3)  # (123, 456, 123, 456, 123, 456)

print(123 in t3)  # True
print(456 not in t3)  # False

4. Built-in methods

Tuple is not to change the size and content, only countand indexboth methods.

【example】

t = (1, 10.31, 'python')
print(t.count('python'))  # 1
print(t.index(10.31))  # 1
  • count('python')Tuple is recorded in tthe element appears several times, it is clear that once
  • index(10.31)This element is found in the tuple tindex it is clearly 1

5. Unpack the tuple

[Example] Unpack one-dimensional tuples (there are several elements left parentheses define several variables)

t = (1, 10.31, 'python')
(a, b, c) = t
print(a, b, c)
# 1 10.31 python

[Example] Decompress two-dimensional tuples (define variables according to the tuple structure in the tuple)

t = (1, 10.31, ('OK', 'python'))
(a, b, (c, d)) = t
print(a, b, c, d)
# 1 10.31 OK python

[Example] If you only want a few elements in the tuple, use the wildcard character "*", which is called wildcard in English, which represents one or more elements in computer language. The following example is a plurality of elements threw restvariable.

t = 1, 2, 3, 4, 5
a, b, *rest, c = t
print(a, b, c)  # 1 2 5
print(rest)  # [3, 4]

[Example] If you don't care about the rest variable at all, then use the wildcard "*" and the underscore "_".

t = 1, 2, 3, 4, 5
a, b, *_ = t
print(a, b)  # 1 2

Practice questions :

1. The concept of tuples

Write the execution result of the following code and the type of the final result

(1, 2)*2
(1, )*2
(1)*2

Analyze why there is such a result.

2. What is the unpacking process?

a, b = 1, 2

Is the above process unpacking?

When unpacking an iterable object, how to assign a value to the placeholder?

Practice personal answers :

6 exercises

6.1

# 列表操作练习
lst = [2,5,6,7,8,9,2,9,9]

#01
lst.append(15)
print(lst)
[2, 5, 6, 7, 8, 9, 2, 9, 9, 15]
#02
lst.insert(len(lst)//2,20)
print(lst)
[2, 5, 6, 7, 8, 20, 9, 2, 9, 9, 15]
#03
lst.extend([2,5,6])
print(lst)
[2, 5, 6, 7, 8, 20, 9, 2, 9, 9, 15, 2, 5, 6]
#04
lst.pop(3)
print(lst)
[2, 5, 6, 8, 20, 9, 2, 9, 9, 15, 2, 5, 6]
#05
lst.reverse()
print(lst)
[6, 5, 2, 15, 9, 9, 2, 9, 20, 8, 6, 5, 2]
#06
lst.sort()
print(lst)
lst.sort(reverse=True)
print(lst)
[2, 2, 2, 5, 5, 6, 6, 8, 9, 9, 9, 15, 20]
[20, 15, 9, 9, 9, 8, 6, 6, 5, 5, 2, 2, 2]

6.2

lst = [1,[4,6],True]
lst[0] = lst[0]*2
lst[1][0] = lst[1][0]*2
lst[1][1] = lst[1][1]*2
print(lst)
[2, [8, 12], True]

6.3

# leetcode 852题 山脉数组的峰顶索引

# 山脉数组定义
# (1)数组k长度大于或等于3    (最大元素具有唯一性)
# (2)存在i,0<=i<=n 且 k[0]<k[1]……k[i-1]<k[i]>k[i+1]>……k[n]

def mountainArray(a):
    list1 = a[:]
    list1.sort()
    ismountain = False
    if list1.count(list1[-1])==1:   # 判断最大值是否唯一
        i = a.index(list1[-1])  # 获取最大值对应原列表索引
        # 构造对比列表
        list_left = a[:i+1]
        list_left.sort()
    
        list_right = a[i:]
        list_right.sort(reverse=True)
        # 判断是否是山脉
        if((list_left==a[:i+1]) and (list_right==a[i:])):
            # 利用集合无重复项,判断山脉两侧是否有重复
            if(len(list_left)==len(set(a[:i+1])) and len(list_right)==len(set(a[i:]))): 
                ismountain = True
    return ismountain

print(mountainArray([1, 3, 4, 5, 3])) # True
print(mountainArray([1, 2, 4, 6, 4, 5])) # False
True
False

7 exercises

7.1

x = (1,2)*2
print(x,type(x))
(1, 2, 1, 2) <class 'tuple'>
x =(1,)*2
print(x,type(x))
(1, 1) <class 'tuple'>
x = (1)*2
print(x,type(x))
2 <class 'int'>

7.2

a,b = 1,2
print(a,b)
1 2
x =1,2
a,b = x
print(x,type(x))
print(a,type(a))
print(b,type(b))
(1, 2) <class 'tuple'>
1 <class 'int'>
2 <class 'int'>

Guess you like

Origin blog.csdn.net/Han_Panda/article/details/113092339