1. 列表
a. 标志
列表(list)在Python的语法中是一种有序且长度可变的集合,可以随时对其中的元素进行添加、删除和修改。
列表通过[]包含,分隔的元素进行初始化,比如我想要列出正在学习Python课程的学生名单:
>>>students = ['Alice', 'Bob', 'Cindy']
>>>students
['Alice', 'Bob', 'Cindy']
也可以直接使用[]来初始化一个不包含任何元素的空列表 >>> 在列表中元素的类型可以不用统一,可以使用列表作为元素:
>>> Basketball = ['科比', 24, ['Jordan', 23]]
>>> Basketball
['科比', 24, ['Jordan', 23]]
b. 基本操作(创建,append( ),pop( ) ,del( ), 拷贝)
classmates = ['boy' , 'girl'] #创建了classmates 的列表
print (classmates)
print(len(classmates))
print('————————————————————————')
# 输出列表的元素与个数
classmates.append('gay')
print (classmates)
print(len(classmates))
print('————————————————————————')
#通过append()添加列表元素并输出
classmates.pop()
print (classmates)
print(len(classmates))
print('————————————————————————')
#通过pop()删除的是列表末的元素
classmates.pop(0)
print (classmates)
print(len(classmates))
print('————————————————————————')
#pop(i)删除的是第i+1个元素
关于del(),del()与pop()的区别是,del()删除的是变量,而pop()删除的是数据。
del( classmates(0) )
del( classmates )
c. 列表相关方法
cmp(list1, list2) 方法用于比较两个列表的元素。
len(list) 方法返回列表元素个数。
max(list) 方法返回列表元素中的最大值。
sort() 函数用于对原列表进行排序,如果指定参数,则使用比较函数指定的比较函数。list.sort(cmp=None, key=None, reverse=False)
remove() 函数用于移除列表中某个值的第一个匹配项用法list.remove(obj)
count() 方法用于统计某个元素在列表中出现的次数。list.count(obj)
2. 元组
a. 标志
另一种有序列表叫元组:tuple。tuple和list非常类似,但是tuple一旦初始化就不能修改。
b. 基本操作(创建及不可变性)
元组(tuple)和列表基本相同,都是有序的序列,其区别在于元组内的元素一旦定义,就不能够再进行修改。
因此元组没有append、insert和pop这些的方法,只能够通过下标对元组内部的元素进行访问。
元组使用()进行初始化。
>>> students = ('Alice', 'Bob', 'Cindy')
>>> students[0]
'Alice'
>>> students.pop()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'pop'
>>> students[1] = 'Dale'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
3. string字符串
a. 定义及基本操作(+,*,读取方式)
一个字符串就是一个字符序列,字符串被广泛应用于Python编程。 字符串是以单引号’或双引号"括起来的任意文本,比如’abc’、"xyz"等。 注意Python不支持单字符类型,单字符也在Python也是作为一个字符串使用。
>>> message = "welcome,boys"
message[0]表示访问message中的第0个字符(小标是从0开始的);message[0:7]从第0个字符到第7个字符(注意不包含第7个字符)构成的字符串,因此得到的是welcome。
>>> message[0:7]
'welcome'
Python中的字符串有两种索引方式,从左往右以0开始,从右往左以-1开始。
>>> message[-1]
‘s’
>>> message[-2]
'y'
+、-、*
>>> a, b = "hello", "boys"
>>> c = a + b
>>> c
'helloboys'
>>> d = a * 3
>>> d
'hellohellohello'
4. 字符串格式化问题
可以使用print()函数的格式化功能。
Python的print()函数支持类似C语言风格的格式化输出。
对于数字和字符串变量来说,在控制台中直接输入变量和输入print(变量名)的效果是一样的:
>>> message = "hellow"
>>> message
'hellow'
>>> print(message)
hellow
现在假设有三个变量:
name = "David"
age = 18
hobby = "篮球"
如果希望打印出这样一句话:
我的名字是David,我今年18岁,我的爱好是篮球
一种写法是:
description = "我的名字是" + name
description = description + ",我今年" + str(age) + "岁"
description = description + ",我的爱好是" + "篮球"
print(description)
需要通过str()函数将age转换成字符串类型。
这样写不但比较麻烦,而且字符串的拼接效率也是非常低的,使用format方法可以这样写:
aaa = "我的名字是%s,我今年%d岁"
print(aaa % (name, age))
百分号是一个格式化的运算符。
其中的%s和%d表示将会用字符串和整数的值来替代它们。
以下为常见的格式化字符
字符 用以格式化的数据类型
d 整数型(10进制 )
c 单个字符
b Boolean值
s 字符串
f 浮点数(10进制)
e 浮点数(科学计数)
x 整数(16进制)
X 整数(16进制)大写