tuple objects

今天来梳理一下Python tuple类型的知识点,特此申明下面信息均参考自公司培训课PPT Nagiza F. Samatova, NC State Univ. All rights,主要涉及到下面几个点:

  • • Immutable sequence of objects
  • • Items: heterogeneous type and non-unique
  • • Named tuples
  • • Tuple operations

immutable: Content cannot be changed by adding, deleting, and altering items

new_tup = (3, 5, 2, 8) 
new_tup[0] = 1
# output:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-515-0b043ae6152f> in <module>
      1 new_tup = (3, 5, 2, 8)
----> 2 new_tup[0] = 1

TypeError: 'tuple' object does not support item assignment

但是tuple可以包含mutable的元素,而且可以修改mutable元素的value

list_tuple = ([8, 7, 5], [1.8, 7.6, 3.5]) 
dics_tuple = ({
    
    'name':'Lu', 'age':24}, {
    
    'car':'BMW', 'y':2015}) 

print('original list_tuple:\n {}'.format(list_tuple))
print('original dics_tuple:\n {}'.format(dics_tuple))
list_tuple[0][1] = 1
dics_tuple[0]['age'] = 30

print('list_tuple after chang:\n {}'.format(list_tuple))
print('dics_tuple after change:\n {}'.format(dics_tuple))

# output:
original list_tuple:
 ([8, 7, 5], [1.8, 7.6, 3.5])
original dics_tuple:
 ({
    
    'name': 'Lu', 'age': 24}, {
    
    'car': 'BMW', 'y': 2015})
list_tuple after chang:
 ([8, 1, 5], [1.8, 7.6, 3.5])
dics_tuple after change:
 ({
    
    'name': 'Lu', 'age': 30}, {
    
    'car': 'BMW', 'y': 2015})

Named Tuples

● Use names instead of numerical indices to access items

用名字取代index访问tuple

● Created by using the namedtuple()factory function. The arguments are the name of the new class and a string containing the names of the elements

用到namedtuple() factory function
namedtuple(‘class name’, ‘the attibute of the class’)

from collections import namedtuple
Pet = namedtuple('Pet', 'kind name age')
dog = Pet(kind='dog', name='Tom', age=2)
cat = Pet(kind='cat', name='Snow', age=3)
print ('dog pet:\nkind:{}\tname:{}\tage:{}'.format(dog.kind, dog.name, dog.age))
print ('cat pet:\nkind:{}\tname:{}\tage:{}'.format(cat.kind, cat.name, cat.age))
# output:
dog pet:
kind:dog	name:Tom	age:2
cat pet:
kind:cat	name:Snow	age:3

Tuples: Operations

Operation Description Result
len() Length of the tuple len(tup_1)
Concatenation(+) Concatenate two tuples into a third one tup_1 + tup_2
Membership check (in) Return True if item is in the tuple 8 in tup_1
tup_1 = (5, 8, 9) 
tup_2 = (4, 3) 
print (len(tup_1)) 
print (tup_1 + tup_2) 
print (8 in tup_1) 
print (tup_2 * 3)
# output:
3
(5, 8, 9, 4, 3)
True
(4, 3, 4, 3, 4, 3)

Tuple: access and slice

nums = (0, 1, 2, 3, 4, 5, 6, 7) 
print(nums[4]) 
print(nums[-5]) 
print(nums[:3]) 
print(nums[-6:-3])
print(nums[7:1:-2])
 
# output:
4
3
(0, 1, 2)
(2, 3, 4)
(753

Create tuple object

empty tuple:

t = ()
t = tuple()

tuple(another_object)–有些python版本可能不支持

t1 = ('a',)
list_obj=[1,2,3,4,5,6]
t2 = tuple(list_obj)
t3 = 'a', 2, ['one', 'two']
t4 = tuple()
t4 = t4 + tuple('one')
print(t1)
print(t2)
print(t3)
print(t4)
# output:
('a',)
(1, 2, 3, 4, 5, 6)
('a', 2, ['one', 'two'])
('o', 'n', 'e')

count(value)
Returns the number of occurrences of an element in a tuple

t = (2,1,2,3,4,2)
print(t.count(2)) #output: 3

index(value)
Searches for the given element in a tuple and returns its position.
第一次出现的位置

t = (2,1,2,3,4,2)
print(t.index(2)) #output 0

猜你喜欢

转载自blog.csdn.net/wumingxiaoyao/article/details/108999468