数据结构

1、列表

list是处理一组有序项目的数据结构,即可以在一个列表中存储一个 序列 的项目。

列表中的项目应该包括在方括号中,在每个项目之间用逗号分割,这样Python就知道是在指明一个列表。一旦创建了一个列表,可以添加、删除或是搜索列表中的项目。由于可以增加或删除项目,我们说列表是 可变的 数据类型,即这种类型是可以被改变的。

# Filename: using_list.py

# This is my shopping list

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

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

print 'These items are:'# Notice the comma at end of the line
for item in shoplist:
    print item,

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]
olditem = shoplist[0]
del shoplist[0]
print 'I bought the', olditem
print 'My shopping list is now', shoplist

输出

$ python using_list.py
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 shopping 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']

可以在列表中添加 任何种类的对象 包括数甚至其他列表。

注意,在print语句的结尾使用了一个 逗号 来消除每个print语句自动打印的换行符。

再接下来,使用列表的sort方法来对列表排序,这个方法影响列表本身,而不是返回一个修改后的列表——这与字符串工作的方法不同。这就是所说的列表是 可变的 而字符串是 不可变的 。

指出想要删除列表中的哪个项目,用del语句从列表中删除它。


2、元组

元组和列表十分类似,只不过元组和字符串一样是 不可变的 即不能修改元组。元组通过圆括号中用逗号分割的项目定义。元组通常用在使语句或用户定义的函数能够安全地采用一组值的时候,即被使用的元组的值不会改变。

# Filename: using_tuple.py

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

new_zoo = ('monkey''dolphin', zoo)
print 'Number of animals 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]
print 'Last animal brought from old zoo is', new_zoo[2][2]

输出

$ python using_tuple.py
Number of animals in the zoo is 3
Number of animals in the new zoo is 3
All animals in new zoo are ('monkey', 'dolphin', ('wolf', 'elephant', 'penguin'))
Animals brought from old zoo are ('wolf', 'elephant', 'penguin')
Last animal brought from old zoo is penguin

变量zoo是一个元组,我们看到len函数可以用来获取元组的长度,这也表明元组也是一个序列。注意元组之内的元组不会失去它的身份。

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

含有0个或1个项目的元组。一个空的元组由一对空的圆括号组成,如myempty = ()。然而,含有单个元素的元组就不那么简单了。必须在第一个(唯一一个)项目后跟一个逗号,这样Python才能区分元组和表达式中一个带圆括号的对象。即如果想要的是一个包含项目2的元组的时候,应该指明singleton = (2 , )


元组最通常的用法是用在打印语句中。

# Filename: print_tuple.py

age = 22
name = 'Swaroop'

print '%s is %d years old' % (name, age)
print 'Why is %s playing with that python?' % name

输出

$ python print_tuple.py
Swaroop is 22 years old
Why is Swaroop playing with that python?

print语句可以使用跟着%符号的项目元组的字符串。这些字符串具备定制的功能。定制让输出满足某种特定的格式。定制可以是%s表示字符串或%d表示整数。元组必须按照相同的顺序来对应这些定制。

观察使用的第一个元组,我们首先使用%s,这对应变量name,它是元组中的第一个项目。而第二个定制是%d,它对应元组的第二个项目age

Python在这里所做的是把元组中的每个项目转换成字符串并且用字符串的值替换定制的位置。因此%s被替换为变量name的值,依此类推。

在第二个print语句中,使用了一个定制,后面跟着%符号后的单个项目——没有圆括号。这只在字符串中只有一个定制的时候有效。


3、字典

字典把联系在一起。注意,键必须是唯一的,就像如果有两个键相同的话,无法找到正确的值。

注意,只能使用不可变的对象(比如字符串)来作为字典的键,但是可以不可变或可变的对象作为字典的值。应该只使用简单的对象作为键。

键值对在字典中以这样的方式标记:d = {key1 : value1, key2 : value2 }。注意它们的键/值对用冒号分割,而各个对用逗号分割,所有这些都包括在花括号中。

记住字典中的键/值对是没有顺序的。如果想要一个特定的顺序,那么应该在使用前自己对它们排序。字典是dict类的实例/对象。

# Filename: using_dict.py

# 'ab' is short for 'a'ddress'b'ook


ab = {       'Swaroop'   'swaroopch@byteofpython.info',
             'Larry'     'larry@wall.org',
             'Matsumoto' 'matz@ruby-lang.org',
             'Spammer'   'spammer@hotmail.com'
     }

print "Swaroop's address is %s" % ab['Swaroop']

# Adding a key/value pair
ab['Guido'] = 'guido@python.org'

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

print '\nThere are %d contacts in the address-book\n' len(ab)
for name, address in ab.items():
    print 'Contact %s at %s' % (name, address)

if 'Guido' in ab: # OR ab.has_key('Guido')
    print "\nGuido's address is %s" % ab['Guido']

输出

$ python using_dict.py
Swaroop's address is swaroopch@byteofpython.info

There are 4 contacts in the address-book

Contact Swaroop at swaroopch@byteofpython.info
Contact Matsumoto at matz@ruby-lang.org
Contact Larry at larry@wall.org
Contact Guido at guido@python.org

Guido's address is guido@python.org

可以使用del语句来删除键/值对,只需要指明字典和用索引操作符指明要删除的键,然后把它们传递给del语句就可以了。执行这个操作的时候,我们无需知道那个键所对应的值。

接下来,使用字典的items方法,来使用字典中的每个键/值对。这会返回一个元组的列表,其中每个元组都包含一对项目——键与对应的值。抓取这个对,然后分别赋给for..in循环中的变量nameaddress然后在for-块中打印这些值。

可以使用in操作符来检验一个键/值对是否存在,或者使用dict类的has_key方法。


4、序列

列表、元组和字符串都是序列,序列的两个主要特点是索引操作符和切片操作符。索引操作符让我们可以从序列中抓取一个特定项目。切片操作符让我们能够获取序列的一个切片,即一部分序列。

# Filename: seq.py

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

# Indexing or 'Subscription' operation
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]

# Slicing on a list
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[:]

# Slicing on a string
name = 'swaroop'
print 'characters 1 to 3 is', name[1:3]
print 'characters 2 to end is', name[2:]
print 'characters 1 to -1 is', name[1:-1]
print 'characters start to end is', name[:]

输出

$ python seq.py
Item 0 is apple
Item 1 is mango
Item 2 is carrot
Item 3 is banana
Item -1 is banana
Item -2 is carrot
Item 1 to 3 is ['mango', 'carrot']
Item 2 to end is ['carrot', 'banana']
Item 1 to -1 is ['mango', 'carrot']
Item start to end is ['apple', 'mango', 'carrot', 'banana']
characters 1 to 3 is wa
characters 2 to end is aroop
characters 1 to -1 is waroo
characters start to end is swaroop


如何使用索引来取得序列中的单个项目(下标操作):每当用方括号中的一个数来指定一个序列的时候,Python会抓取序列中对应位置的项目。记住,Python从0开始计数。因此,shoplist[0]抓取第一个项目,shoplist[3]抓取shoplist序列中的第四个元素。

索引同样可以是负数,在那样的情况下,位置是从序列尾开始计算的。因此,shoplist[-1]表示序列的最后一个元素而shoplist[-2]抓取序列的倒数第二个项目。

切片操作符是序列名后跟一个方括号,方括号中有一对可选的数字,并用冒号分割。注意这与使用的索引操作符十分相似。记住数是可选的,而冒号是必须的

切片操作符中的第一个数(冒号之前)表示切片开始的位置,第二个数(冒号之后)表示切片到哪里结束。如果不指定第一个数,Python就从序列首开始。如果没有指定第二个数,则Python会停止在序列尾。注意,返回的序列从开始位置 开始 ,刚好在 结束 位置之前结束。即开始位置是包含在序列切片中的,而结束位置被排斥在切片外

可以用负数做切片。负数用在从序列尾开始计算的位置。例如,shoplist[:-1]会返回除了最后一个项目外包含所有项目的序列切片。

序列的神奇之处在于你可以用相同的方法访问元组、列表和字符串。


5、参考

创建一个对象并给它赋一个变量的时候,这个变量仅仅 参考 那个对象,而不是表示这个对象本身!也就是说,变量名指向计算机中存储那个对象的内存。这被称作名称到对象的绑定

# Filename: reference.py

print 'Simple Assignment'
shoplist = ['apple''mango''carrot''banana']
mylist = shoplist # mylist is just another name pointing to the same object!

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


print 'Copy by making a full slice'
mylist = shoplist[:] # make a copy by doing a full slice
del mylist[0# remove first item

print 'shoplist is', shoplist
print 'mylist is', mylist
# notice that now the two lists are different

输出

$ python reference.py
Simple Assignment
shoplist is ['mango', 'carrot', 'banana']
mylist is ['mango', 'carrot', 'banana']
Copy by making a full slice
shoplist is ['mango', 'carrot', 'banana']
mylist is ['carrot', 'banana']

如果想要复制一个列表或者类似的序列或者其他复杂的对象(不是如整数那样的简单 对象 ),那么必须使用切片操作符来取得拷贝。如果只是想要使用另一个变量名,两个名称都 参考 同一个对象,那么如果不小心的话,可能会引来各种麻烦。

6、字符串

# Filename: str_methods.py

name = 'Swaroop' # This is a string object 

if name.startswith('Swa'):
    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)

输出

$ python str_methods.py
Yes, the string starts with "Swa"
Yes, it contains the string "a"
Yes, it contains the string "war"
Brazil_*_Russia_*_India_*_China

startwith方法是用来测试字符串是否以给定字符串开始。in操作符用来检验一个给定字符串是否为另一个字符串的一部分。

find方法用来找出给定字符串在另一个字符串中的位置,或者返回-1以表示找不到子字符串。str类也有以一个作为分隔符的字符串join序列的项目的整洁的方法,它返回一个生成的大字符串。


7、列表综合

通过列表综合,可以从一个已有的列表导出一个新的列表。

# Filename: list_comprehension.py

listone = [234]
listtwo = [2*i for in listone if i > 2]
print listtwo

输出

$ python list_comprehension.py
[6, 8]

这里为满足条件( if i > 2 )的数指定了一个操作( 2*i ),从而导出一个新的列表。注意原来的列表并没有发生变化。


8、在函数中接收元组和列表

当要使函数接收元组或字典形式的参数的时候,有一种特殊的方法,它分别使用***前缀。这种方法在函数需要获取可变数量的参数的时候特别有用。

>>> def powersum(power, *args):
...     '''Return the sum of each argument raised to specified power.'''
...     total = 0
...     for i in args:
...          total += pow(i, power)
...     return total
...
>>> powersum(2, 3, 4)
25

>>> powersum(2, 10)
100

由于在args变量前有*前缀,所有多余的函数参数都会作为一个元组存储在args中。如果使用的是**前缀,多余的参数则会被认为是一个字典的键/值对。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 适合毕业设计、课程设计作业。这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。 所有源码均经过严格测试,可以直接运行,可以放心下载使用。有任何使用问题欢迎随时与博主沟通,第一时间进行解答!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值