Python数据结构2,字符串、词典

本文介绍了Python中的字符串和词典数据结构。字符串部分讲解了内置函数,如find、capitalize、center等。词典部分讨论了如何定义和操作词典,包括使用zip函数结合列表创建词典以及内置函数如clear、values、keys和items。
摘要由CSDN通过智能技术生成

数据结构 - 2

1. 字符串

字符串是基于文本的有序数据,用单/双/三重引号括起来表示。

String0 = 'Taj Mahal is beautiful'
String1 = "Taj Mahal is beautiful"
String2 = '''Taj Mahal
is
beautiful'''
String3 = """Multi-line
string"""
print(String0, type(String0))
print(String1, type(String1))
print(String2, type(String2))
print(String3, type(String3))
Taj Mahal is beautiful <class 'str'>
Taj Mahal is beautiful <class 'str'>
Taj Mahal
is
beautiful <class 'str'>
Multi-line
string <class 'str'>

字符串索引和分段类似于前面详细解释过的列表。

print(String0[4])
print(String0[4:])
print(String0[-1])
M
Mahal is beautiful
l

1.1 内置函数

find( ) 函数返回要在字符串中找到的给定数据的索引值。如果没有找到它,它返回 -1。请注意不要将返回的-1与反向索引值混淆。

print(String0)
print(String0.find('al'))
print(String0.find('am'))
Taj Mahal is beautiful
7
-1

返回的索引值是输入数据中第一个元素的索引。

print(String0[7])
a

还可以输入find() 函数,在它们之间搜索索引值。

print(String0.find('j',1))
print(String0.find('j',1,3))
2
2

capitalize( ) 用于将字符串中的第一个元素大写。

String3 = 'observe the first letter in this sentence. can you change this sentence'
print(String3.capitalize())
Observe the first letter in this sentence. can you change this sentence

center( ) 用于通过指定字段宽度将字符串居中对齐。

String0.center(70)
'                        Taj Mahal is beautiful                        '

One can also fill the left out spaces with any other character.

String0.center(70,'-')
'------------------------Taj Mahal is beautiful------------------------'

zfill( ) 通过指定字段宽度来填充零。

String0.zfill(30)
'00000000Taj Mahal is beautiful'

expandtabs( ) 允许您更改制表符的间距。'\t'默认设置为8个空格。

s = 'h\te\tl\tl\to'
print(s)
print(s.expandtabs(1))
print(s.expandtabs(4))
h	e	l	l	o
h e l l o
h   e   l   l   o

index( )find( ) 函数的工作方式相同,唯一的区别在于 find( ) 返回 -1,当输入元素在字符串中没有找到,但是index( ) 函数会抛出一个 ValueError异常。

print(String0.index('Taj'))
print(String0.index('Mahal',0))
print(String0.index('Mahal',10,20))
0
4
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-17-146ef93bc1cd> in <module>()
      1 print(String0.index('Taj'))
      2 print(String0.index('Mahal',0))
----> 3 print(String0.index('Mahal',10,20))

ValueError: substring not found

endswith( ) 函数用于检查给定字符串是否以作为输入的特定字符结尾。

print(String0.endswith('y'))
False

还可以指定开始和停止索引值。

print(String0.endswith('l',0))
print(String0.endswith('M',0,5))
True
True

count( ) 函数计算给定字符串中的字符数。也可以指定开始和停止索引或将其留空。(这些是隐式参数,将在函数中处理)

print(String0.count('a',0))
print(String0.count('a',5,10))
4
2

join( ) 函数在输入字符串的元素之间添加一个字符。

'a'.join('*_-')
'*a_a-'
'\n'.join(['1', '2'])
'1\n2'

'*_-' 是输入字符串而字符'a'被添加在每一个元素之间。

join( ) 函数也可以被用来将列表转化为字符串。

a = list(String0)
print(a)
b = ''.join(a)
print(b)
['T', 'a', 'j', ' ', 'M', 'a', 'h', 'a', 'l', ' ', 'i', 's', ' ', 'b', 'e', 'a', 'u', 't', 'i', 'f', 'u', 'l']
Taj Mahal is beautiful

在将它转化成字符串之前,join( ) 函数可以被用来在列表元素中插入任意的字符。

c = '/'.join(a)[18:]
print(c)
 /i/s/ /b/e/a/u/t/i/f/u/l

split( ) 函数被用来将一个字符串转化为列表。把它想成与join() 相反地函数。

d = c.split('/')
print(d)
[' ', 'i', 's', ' ', 'b', 'e', 'a', 'u', 't', 'i', 'f', 'u', 'l']

split( ) 函数中,还可以指定分割字符串的次数,或者新返回列表应该包含的元素数量。元素的数量总是比指定的数量多1,这是因为它被分割了指定的次数。

e = c.split('/',3)
print(e)
print(len(e))
[' ', 'i', 's', ' /b/e/a/u/t/i/f/u/l']
4

lower( ) 将任何大写字母转换为小写字母。

print(String0)
print(String0.lower())
Taj Mahal is beautiful
taj mahal is beautiful

upper( ) 将任何小写字母转换为大写字母。

String0.upper()
'TAJ MAHAL IS BEAUTIFUL'

replace( ) 函数将该元素替换为另一个元素。

String0.replace('Taj Mahal','Bengaluru')
'Bengaluru is beautiful'

strip( ) 函数用于从右端和左端删除不需要的元素。

f = '    hello      '

如果没有指定字符,那么它将删除数据左边和右边的所有空格。

f.strip()
'hello'

strip( ) 函数,当指定字符时,如果该字符出现在指定字符串的两端,则删除该字符。

f = '   ***----hello---*******     '
f.strip(' *-')
'hello'

必须删除星号,但没有。这是因为在左边和右边都有一个空格。在strip函数中。字符需要按照它们出现的特定顺序输入。

print(f.strip(' *'))
print(f.strip(' *-'))
----hello---
hello

lstrip( )rstrip( ) 函数具有与strip函数相同的功能,但唯一的区别是lstrip() 只删除左边的内容,而rstrip() 只删除右边的内容。

print(f.lstrip(' *'))
print(f.rstrip(' *'))
----hello---*******     
   ***----hello---

2. 词典

词典更像数据库,因为在这里你可以用用户定义的字符串索引特定的序列。

为了定义一个词典,让一个变量赋值为 { }dict()

d0 = {}
d1 = dict()
print(type(d0), type(d1))
<class 'dict'> <class 'dict'>

词典的工作方式有点像列表,但增加了分配自己索引样式的功能。

d0['One'] = 1
d0['OneTwo'] = 12 
print(d0)
{'One': 1, 'OneTwo': 12}
d1 = {"key1":1, "key2":[1,2,4], 3:(1, 4, 6)}
print(d1)
{'key1': 1, 'key2': [1, 2, 4], 3: (1, 4, 6)}

这就是字典的样子。现在你可以通过设为 'One' 的索引值来访问 1

print(d0['One'])
1

两个相关的列表可以合并成一个词典。

names = ['One', 'Two', 'Three', 'Four', 'Five']
numbers = [1, 2, 3, 4, 5]

zip( ) 函数用来结合两个列表。

d2 = zip(names,numbers)
print(dict(d2))
{'One': 1, 'Three': 3, 'Five': 5, 'Four': 4, 'Two': 2}
d3 = {names[i]:numbers[i] for i in range(len(names))}
print(d3)
{'One': 1, 'Three': 3, 'Five': 5, 'Four': 4, 'Two': 2}

这两个列表组合成一个列表,每个元素都与元组中来自另一个列表的各自元素相连。

进一步地,为了将上面的内容转化为词典。我们可以使用 dict( ) 函数。

d2 = zip(names,numbers)

a1 = dict(d2)
print(a1)
{'One': 1, 'Four': 4, 'Three': 3, 'Five': 5, 'Two': 2}

2.1 内置函数

clear( ) 函数被用于擦除所创建的整个词典。

a1 = {1:10, 2:20}
a1.clear()
print(a1)
{}

词典也可以使用循环来构建。

a1 = {names[i]:numbers[i] for i in range(len(names))}
print(a1)
{'One': 1, 'Three': 3, 'Five': 5, 'Four': 4, 'Two': 2}
for i in range(len(names)):
    a1[names[i]] = numbers[i]
print(a1)
{'One': 1, 'Three': 3, 'Five': 5, 'Four': 4, 'Two': 2}

values( ) 函数返回了一个包含词典中所有赋值的列表

a1.values()
dict_values([1, 3, 5, 4, 2])

keys( ) 函数返回包含赋值的所有索引或键。

a1.keys()
dict_keys(['One', 'Three', 'Five', 'Four', 'Two'])

items() 返回一个列表同时也包含该列表,但是词典中的每个元素都在一个元组中。这与使用zip函数得到的结果相同。

a1.items()

for (k,v) in a1.items():
    print("[%6s] %d" % (k, v))
[   One] 1
[ Three] 3
[  Five] 5
[  Four] 4
[   Two] 2

pop() 函数用于删除特定的元素,并且这个删除的元素可以被分配给一个新的变量。但是请记住,只存储值而不存储键,因为它只是一个索引值。

a2 = a1.pop('One')
print(a1)
print(a2)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-55-d348bc398654> in <module>()
----> 1 a2 = a1.pop('One')
      2 print(a1)
      3 print(a2)

KeyError: 'One'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值