您的位置:首页 > 理论基础 > 数据结构算法

Python学习笔记ucas(lecture2)数据结构(字符串、列表、元组、字典、集合)

2018-02-01 11:46 1361 查看

Lecture 2 数据结构(字符串、列表、元组、字典、集合)

目录

Lecture 2 数据结构字符串列表元组字典集合

目录
1序列通用操作

2字符串

3列表

4元组

5字典

6集合

1序列通用操作





print(str(123.45))
print(list("hello,world!"))
print(tuple("hello,world!"))


123.45

[‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘,’, ‘w’, ‘o’, ‘r’, ‘l’, ‘d’, ‘!’]

(‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘,’, ‘w’, ‘o’, ‘r’, ‘l’, ‘d’, ‘!’)

a="malele"
print(len(a))
print(sorted(a))


6

[‘a’, ‘e’, ‘e’, ‘l’, ‘l’, ‘m’]



2字符串













# 1、拆分字符串
s = 'www.google.com'
print(s.partition('.'))
print(s.rpartition('.'))
print(s.split('.'))


(‘www’, ‘.’, ‘google.com’)

(‘www.google’, ‘.’, ‘com’)

[‘www’, ‘google’, ‘com’]

# 2、设置格式
# 字符串中的{0}和{1}引用format的参数,被替换成相应的字符串或变量
print('{0} likes {1}'.format('jack','ice cream'))
# 可以使用关键字参数
print('{who} {pet} has fleas'.format(pet = 'dog',who = 'my'))


jack likes ice cream

my dog has fleas

# 3、join合并字符串
s = ["hello","world","hello","China"]
r = " ".join(s)   #合并的串用空格分隔
print(r)

se = ['1','2','3','4','5']
p  = '+'
print(p.join(se)) #合并的串用 + 分隔


hello world hello China

1+2+3+4+5

# 4、使用reduce连接字符串
from functools import reduce
import operator                  # 导入模块operator,利用add()方法实现累计连接
s = ["hello ","world ","hello ","China "]
r = reduce(operator.add,s,"  ")    # 实现对空字符串“”的累计连接,每次连接列表s中的一个元素
print(r)


hello world hello China

# 5、时间与字符串转换
import time,datetime
# 将当前时间转换为字符串
print(time.strftime("%Y-%m-%d %X",time.localtime()))


3列表









# 1、在列表尾部添加元素
list1 = ['apple','banana','grape','orange']
print(list1)
list1.append('watermelon')
print(list1)
list2 = ['strawberry','pear']
list1.extend(list2)
print(list1)


[‘apple’, ‘banana’, ‘grape’, ‘orange’]

[‘apple’, ‘banana’, ‘grape’, ‘orange’, ‘watermelon’]

[‘apple’, ‘banana’, ‘grape’, ‘orange’, ‘watermelon’, ‘strawberry’, ‘pear’]

# 2、列表解析
print([x for x in range(10)])
print([x**2 for x in range(10)])
print([x**2 for x in range(10) if x**2<50])
print([(x+1,y+1) for x in range(2) for y in range(2)])


[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

[0, 1, 4, 9, 16, 25, 36, 49]

[(1, 1), (1, 2), (2, 1), (2, 2)]

# 3、输出1-10的平方的列表
result = []
for n in range(1,11):
result.append(n*n)
print(result)

print([x*x for x in range(1,11)])


[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

[1, 4, 9, 16
ccba
, 25, 36, 49, 64, 81, 100]

# 4、列表中使用字符串
print([c for c in 'pizza'])
print([c.upper() for c in 'pizza'])

# 利用列表解析修改现有列表
list1 = ['ai','bi','ci']
print(list1)
list2 = [x.capitalize() for x in list1]
print(list2)


[‘p’, ‘i’, ‘z’, ‘z’, ‘a’]

[‘P’, ‘I’, ‘Z’, ‘Z’, ‘A’]

[‘ai’, ‘bi’, ‘ci’]

[‘Ai’, ‘Bi’, ‘Ci’]

4元组





# 1、列表和元组的比较
list1 = [3,5,2,4]
print(list1)
print(sorted(list1))
print(list1)
list1.sort()
print(list1)


[3, 5, 2, 4]

[2, 3, 4, 5]

[3, 5, 2, 4]

[2, 3, 4, 5]

tuple1 = (3,5,2,4)
print(sorted(tuple1))
print(tuple1)
tuple1.sort()




5字典







6集合



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息