小白教程

 找回密码
 立即注册

集合

发布者: 小白教程

使用集合,您可以测试成员资格,是否是另一个集合的子集,找到两个集合之间的交集,依此类推。

>>> 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'}

这个怎么运作

如果您还记得学校里的基础集合论数学,那么这个例子是不言而喻的。但是,如果没有,您可以使用Google“集合论”和“ Venn图”更好地了解我们在Python中对集合的使用。

参考

当您创建对象并将其分配给变量时,该变量仅引用该对象,并不代表该对象本身!也就是说,变量名称指向计算机内存中存储对象的那部分。这称为将名称绑定到对象。

通常,您不必担心这一点,但是由于需要注意一些引用,因此会产生微妙的影响:

示例(另存为ds_reference.py):

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

# I purchased the first item, so I remove it from the list
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')
# Make a copy by doing a full slice
mylist = shoplist[:]
# Remove first item
del mylist[0]

print('shoplist is', shoplist)
print('mylist is', mylist)
# Notice that now the two lists are different

输出:

$ python ds_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']

这个怎么运作

注释中提供了大多数解释。

请记住,如果要复制列表或此类序列或复杂对象(而不是诸如整数之类的简单对象)的副本,则必须使用切片操作进行复制。如果只是将变量名分配给另一个名称,则它们都将“引用”相同的对象,如果不小心,可能会很麻烦。

给Perl程序员的注释

请记住,列表的赋值语句不会创建副本。您必须使用切片操作来制作序列的副本。

有关字符串的更多信息

前面我们已经详细讨论了字符串。还有什么可以知道的?好吧,您知道字符串也是对象,并且具有执行从检查字符串的一部分到剥离空格的所有操作的方法吗?实际上,您已经在使用字符串方法...该format方法!

您在程序中使用的字符串都是该类的所有对象str下一个示例演示了此类的一些有用方法。有关此类方法的完整列表,请参见help(str)

示例(另存为ds_str_methods.py):

# This is a string object
name = 'Swaroop'

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 ds_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

这个怎么运作

在这里,我们看到了许多字符串方法在起作用。startswith方法用于确定字符串是否以给定的字符串开头。in运算符用于检查一个给定的字符串是字符串的一部分。

find方法用于在字符串中定位给定子字符串的位置。find如果找不到子字符串失败,则返回-1。str类也有一个整洁的方法join与字符串充当序列,并返回来自该产生的更大的串的每个项之间的分隔符序列的项目。

上一篇:序列下一篇:面向对象编程

Archiver|手机版|小黑屋|小白教程 ( 粤ICP备20019910号 )

GMT+8, 2024-9-20 01:44 , Processed in 0.027840 second(s), 18 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc. Template By 【未来科技】【 www.wekei.cn 】

返回顶部