Python基础_数据结构(五)

本文深入介绍了Python中的四种内置数据结构:列表、元组、字典和集合的特点与使用方法。通过示例展示了如何操作这些数据结构,包括排序、索引、切片等常见操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python中有四种内置的数据结构——列表(List)、元祖(Tuple)、字典(Dictionary)和集合(Set)。

列表(List):用来保存一系列有序项目的集合。(可变的)

项目的列表应该用方括号括起来。

shoplist = ['apple', 'mango', 'carrot', 'banana']

print('I have', len(shoplist), 'items to purchase')

print('These items are:', end=' ')
for item in shoplist:
    print(item, end=' ')

print('\nI also have to buy rice')
shoplist.append('rice')
print('My shopping list is now', shoplist)

print('I will sort my list now')
shoplist.sort()
print('Sorted shoppong list is', shoplist)

print('The first item I will buy is', shoplist[0])
olditem = shoplist[0]
del shoplist[0]
print('I bought the', olditem)
print('My shopping list is now', shoplist)

输出:

I have 4 items to purchase
These items are: apple mango carrot banana 
I also have to buy rice
My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice']
I will sort my list now
Sorted shoppong list is ['apple', 'banana', 'carrot', 'mango', 'rice']
The first item I will buy is apple
I bought the apple

My shopping list is now ['banana', 'carrot', 'mango', 'rice']

可以向列表中添加任何类型的对象。


元祖(Tuple):用于将多个对象保存到一起。可以将它们近似地看作列表,但是元祖不能提供列表类能够提供给你的广泛的功能。(不可变的)

指定项目时,你可以给它们加上括号,并在括号内部用逗号进行分隔。(括号非必须)

元祖通常用于保证某一语句或某一用户定义的函数可以安全地采用一组数值,意即元祖内的数值不会改变。

zoo = ('python', 'elephant', 'penguin')
print('Number of animals in the zoo is', len(zoo))

new_zoo = 'monkey', 'camel', zoo
print('Number of cages in the new zoo is', len(new_zoo))
print('All animal in the new zoo are', new_zoo)
print('Animal brought from old zoo is', new_zoo[2])
print('Last animal brought from old zoo is', new_zoo[2][2])
print('Number of animals in the new zoo is',len(new_zoo)-1+len(new_zoo[2]))

输出:

Number of animals in the zoo is 3
Number of cages in the new zoo is 3
All animal in the new zoo are ('monkey', 'camel', ('python', 'elephant', 'penguin'))
Animal brought from old zoo is ('python', 'elephant', 'penguin')
Last animal brought from old zoo is penguin

Number of animals in the new zoo is 5


包含0个项目的元祖:myempty=()

包含一个项目的元祖:你必须在第一个(也是唯一一个)项目的后面加上一个逗号来指定它,如此一来Python才可以识别出这个表达式究竟想表达的是一个元祖还是只是一个被括号所环绕的对象。singleton = (2,)


字典(Dictionary):键值对

键值:只能使用不可变的对象

值:可以使用可变或不可变的对象作为字典的值

d = {key : value1, key2 : value2}

字典中成对的键值对不会以任何方式进行排序。如果希望它们安排一个特别的次序,只能在使用它们之前自行进行排序。

ab = {
    'key1': 'value1',
    'key2': 'value2',
    'key3': 'value3',
    'key4': 'value4'
}

print("key1's value is", ab['key1'])  # key1's value is value1

del ab['key4']

print('\nThere are {} values\n'.format(len(ab)))  # There are 3 values

# key1's value is value1
# key2's value is value2
# key3's value is value3
for key, value in ab.items():
    print("{}'s value is {}".format(key, value))

ab['key5'] = 'value5'

if 'key5' in ab:
    print("key5's value is", ab['key5'])  # key5's value is value5序列

序列(Sequence)

主要功能是资格测试(也就是in与not in表达式)和索引操作,它们能够允许我们直接获取序列中的特定项目。

切片(Slicing)运算符:能够允许我们获得序列中的某段切片——也就是序列之中的一部分。

冒号前面的数字指的是切片开始的位置,冒号后面的数字指的是切片结束的位置。序列切片包括起始位置,不包括结束位置。

shoplist = ['apple', 'mango', 'carrot', 'banana']
name = 'Swaroop'

print(shoplist[0])  # apple
print(shoplist[1])  # mango
print(shoplist[2])  # carrot
print(shoplist[3])  # banana
print(shoplist[-1])  # banana 最后一个
print(shoplist[-2])  # carrot 倒数第二个
print(name[0])  # S

print(shoplist[1:3])  # ['mango', 'carrot']
print(shoplist[2:])  # ['carrot', 'banana']
print(shoplist[1:-1])  # ['mango', 'carrot']
print(shoplist[:])  # ['apple', 'mango', 'carrot', 'banana']

print(name[1:3])  # wa
print(name[2:])  # aroop
print(name[1:-1])  # waroo
print(name[:])  # Swaroop

切片操作中提供第三个参数,这一参数被视为切片的步长(Step)(在默认情况下,步长大小为1)

shoplist = ['apple', 'mango', 'carrot', 'banana']
print(shoplist[::2])  # ['apple', 'carrot']
print(shoplist[::-1])  # ['banana', 'carrot', 'mango', 'apple']


集合(Set):简单对象的无序集合

当集合中的项目存在与否比起次序或其出现次数更加重要时,我们就会使用集合。

bri = set(['brazil', 'russia', 'india'])
print('india' in bri)  # True
print('usa' in bri)  # False

bric = bri.copy()
bric.add('china')
print(bric.issuperset(bri))  # True
bri.remove('russia')
print(bri & bric)  # {'india', 'brazil'}
print(bri.intersection(bric))  # {'india', 'brazil'}


列表的赋值语句不会创建一份副本,你必须使用切片操作来生成一份序列的副本。


有关字符串的更多内容

name = 'Swaroop'

if name.startswith('Swa'):
    print('True')

if 'a' in name:
    print('True')

if name.find('war') != -1:
    print('True')

delimiter = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China']
print(delimiter.join(mylist))  # Brazil_*_Russia_*_India_*_China

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值