A Byte of Python 笔记 (四)数据结构

Python 中有四种内建的数据结构—— 列表、元组、字典和集合


1. 列表

list 是处理一组有序项目的数据结构
列表是可变的数据类型,即这种类型是可以被改变(增加、删除等)的。

列表中的项目应该包括在方括号

列表中添加元素是.append

>>> my_list.append("four")
>>> my_list
[1, 'two', 3, 'four']
对象和类

例如i赋上整数5,你就能将其想作创建了一个类int对象(即,实例)i。

类相当于是一个基础模板,例如一个动物模板,基础的无关。于是制造的动物时可以直接用模板,如果修改则敲代码覆盖,不修改则默认使用类的内容

方法(函数)是就该类而言的。仅当你已经定义了一个该类的对象时,你才能使用这些功能。
Python 给列表提供了允许你在列表的末尾来增加项目的append 方法。
例如,mylist.append(’an item’)会给列表mylist 增加一个字符串。注意用带点的记号来访问对象的方法。

例子:

# This is my shopping list
#输入
shoplist = ['apple', 'mango', 'carrot', 'banana']  # 定义一个列表
print('I have', len(shoplist), 'items to purchase.') # 打印输出
print('These items are:', end=' ') #打印输出,最后跟一个空格

for item in shoplist:  # item为字符串,i为正数
	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 shopping list is', shoplist)  # 打印输出
print('The first item I will buy is', shoplist[0])  # 打印出第一个参数(从0开始)
olditem = shoplist[0]   # 赋值
del shoplist[0]  # 删除第一个参数
print('I bought the', olditem)  # 打印输出
print('My shopping list is now', shoplist)  # 打印输出

del 的注释—— 该语句用于删除变量/名字
dir() 函数能在任何对象上起作用。例如,运行dri(print) 来了解关于print 函数的属性,或者dir(str) 来查看str 类的属性。

2. 元组

定义:通过圆括号中用逗号分割的项目定义

元组和字符串一样是不可变的即你不能修改元组

zoo = ('python', 'elephant', 'penguin') # remember the parentheses are optional
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 animals in new zoo are', new_zoo)
print('Animals brought from old zoo are', new_zoo[2]) # 注意从0开始,于是[2]指的是第三个zoo。
print('Last animal brought from old zoo is', new_zoo[2][2]) # 引用[2]zoo中的第三个[2]
print('Number of animals in the new zoo is',len(new_zoo)-1+len(new_zoo[2]))

对于元组,没有括号也可以(但还是推荐写出来)

我们可以通过一对方括号来指明某个项目的位置从而来访问元组中的项目,就像我们对列表的用法一样。这被称作索引运算符。我们使用new_zoo[2] 来访问new_zoo中的第三个项目。我们使用new_zoo[2][2] 来访问new_zoo 元组的第三个项目的第三个项目。

含有单个元素的元组

含有单个元素的元组,你必须在第一个(唯一一个)项目后跟一个逗号,这样Python 才能区分元组和表达式中一个带圆括号的对象
例如,singleton = (2 ,)

元组和列表的区别:
列表是可变的,而元组是不可变的。 列表有一个 append() 的方法来添加更多的元素,而元组却没有这个方法
在你有一些不确定长度的相同类型队列的时候使用列表;在你提前知道元素数量的情况下使用元组,因为元素的位置很重要。

3. 字典

定义:
字典类似于你通过联系人名字查找地址和联系人详细情况的地址簿,即,我们把键(名字)和值(详细情况)联系在一起。注意,键必须是唯一的,就像如果有两个人恰巧同名的话,你无法找到正确的信息。

Note:

必须使用不可变的对象(比如字符串)来作为字典的键,但是可以把不可变或可变的对象作为字典的值
键/值对是没有顺序的

用法:
键/值对用冒号分割,而各个对用逗号分割,所有这些都包括在花括号中。

字典是dict 类的实例/对象。

ab = { 'Swaroop' : 'swaroop@swaroopch.com',
	'Larry' : 'larry@wall.org',
	'Matsumoto' : 'matz@ruby-lang.org',
	'Spammer' : 'spammer@hotmail.com'
}  #键值对用冒号分割

print("Swaroop's address is", ab['Swaroop'])  #打印输出,可以用[]来引用字典内的内容

# Deleting a key-value pair
del ab['Spammer']

print('\nThere are {0} contacts in the address-book\n'.format(len(ab)))

for name, address in ab.items():  #for循环中,变量名(name,address)是任意的
	print('Contact {0} at {1}'.format(name, address))

添加键值对

ab['Guido'] = 'guido@python.org'
if 'Guido' in ab: # OR ab.has_key('Guido')
	print("\nGuido's address is", ab['Guido'])

4. 序列

列表、元组和字符串都是序列。不是一个新的类型
序列的主要特点是索成员检验(例如,在和不在表达式中)和索引操作符,索引操作符让我们可以直接从序列中抓取一个特定项目。

索引同样可以是负数,在那样的情况下,位置是从序列尾开始计算的。

shoplist = ['apple', 'mango', 'carrot', 'banana'] # 列表
name = 'swaroop'  # 字符串

print('Item 0 is', shoplist[0])
print('Item 1 is', shoplist[1])
print('Item 2 is', shoplist[2])
print('Item 3 is', shoplist[3])
print('Item -1 is', shoplist[-1])
print('Item -2 is', shoplist[-2])  #打印列表的倒数第三个字符
print('Character 0 is', name[0])  #打印字符串的第一个字符
#切片
print('Item 1 to 3 is', shoplist[1:3])
print('Item 2 to end is', shoplist[2:])
print('Item 1 to -1 is', shoplist[1:-1])
print('Item start to end is', shoplist[:])

切片操作符
索引操作符
均为方括号[]内放置数字。如果不指定第一个数,Python 就从序列首开始。如果没有 指定第二个数,则Python 会停止在序列尾。
Note:

  1. 1:3是指第一个到第三个,不包括第三个。且是从0开始计数

    shoplist[1:3] 返回从位置1 开始,包括位置2,但是停止在位置3 的一个序列切片,因此返回一个含有两个项目的切片。
    
  2. 也可以给切片规定第三个参数,就是切片的步长(默认步长是1)

>>> shoplist = ['apple', 'mango', 'carrot', 'banana']
>>> shoplist[::1]
['apple', 'mango', 'carrot', 'banana']
>>> shoplist[::2]
['apple', 'carrot']
>>> shoplist[::3]
['apple', 'banana']
>>> shoplist[::-1]
['banana', 'carrot', 'mango', 'apple']

5. 集合

使用集合,可以检查是否是成员,是否是另一个集合的子集,得到两个集合的交集等等。

>>> bri = set(['brazil', 'russia', 'india'])
>>> 'india' in bri
True
>>> 'usa' in bri
False
>>> bric = bri.copy()
>>> bric.add('china')
>>> bric.issuperset(bri)
True
>>> bri.remove('russia')
>>> bri & bric # OR bri.intersection(bric)
{'brazil', 'india'}

6. 引用

片段 1 引用一个变量。
print('Simple Assignment')
shoplist = ['apple', 'mango', 'carrot', 'banana']
mylist = shoplist   # mylist指向了另一个变量,称作引用

del shoplist[0] # 删除被指向(引用)的那个变量的元素

print('shoplist is', shoplist)
print('mylist is', mylist)
# notice that both shoplist and mylist both print the same list without the 'apple' confirming that they point to the same object
片段 2 复制变量内容到一个新变量中
print('Copy by making a full slice')
mylist = shoplist[:]
del mylist[0]

print('shoplist is', shoplist)
print('mylist is', mylist)
# 打印两个变量内容不一样。mylist少了第一个

注意第二个片段是把里面内容的切片赋予变量,两个之间没有关联。而第一个片段是引用。

7. 关于字符串

字符串也是对象,同样具有方法。这些方法可以完成包括检验一部分字符串和去除空格在内的各种工作
在程序中使用的字符串都是str 类的对象。

name = 'Swaroop' # This is a string object

if name.startswith('Swa'):   # name不是特定的名字。
	print('Yes, the string starts with "Swa"')

if 'a' in name: 
	print('Yes, it contains the string "a"')
	
if name.find('war') != -1:  # (逻辑值)
	print('Yes, it contains the string "war"')

delimiter = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China']
print(delimiter.join(mylist))

可以在变量名后加.startwith \ .find等对字符串操作的函数作为标间

startwith 方法是用来测试字符串是否以给定字符串开始。in 操作符用来检验一个给定字符串是否为另一个字符串的一部分。
find 方法用来找出给定字符串在另一个字符串中的位置,或者返回-1 以表示找不到子字符串。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值