LIST 列表
1、判断列表是否为空
Python中判断list是否为空有以下两种方式:
# way1
list_temp = []
if len(list_temp):
# 存在值即为真,返回的是列表的元素个数;
else:
# list_temp是空的
# way2
list_temp = []
if list_temp:
# 存在值即为真
else:
# list_temp是空的
以上两种方法均可以判断出 list_temp 列表是否是空列表,第二个方法要优于第一个方法,在Python中,False,0,'',[],{},()都可以视为假
2、向列表中添加、删除元素
list.append(element)
del list[1] # 删除列表中序号为1的元素
list.remove('aa') # 删除列表中'aa'的第一个匹配项
3、遍历列表
基本遍历
if __name__ == '__main__':
list = ['html', 'js', 'css', 'python']
# 方法1 从1开始显示序号
print '遍历列表方法1:'
for i in list:
print ("序号:%s 值:%s" % (list.index(i) + 1, i))
print '\n遍历列表方法2:'
# 方法2 从1开始显示序号
for i in range(len(list)):
print ("序号:%s 值:%s" % (i + 1, list[i]))
# range为左闭右开,将range(5)时,实为从0到4
在遍历时删除满足条件的元素
for i in range(len(list)-1, -1, -1):
if list[i] in list_use:
del list[i]
字典
1、遍历字典
dict={'a':1,'b':2,'c':3}
# way1 遍历键
for key in dict.keys():
# 等价于 dict.keys()
print(key+":"+dict[key]
a:1
b:2
c:3
# way2 遍历值
for value in dict.values():
print(value)
1
2
3
# way3 遍历字典项
for kv in dict.items():
print(kv)
('a',1)
('b',2)
('c',3)
# way4 遍历字典键值
for key,value in dict.items():
print(key+':'+value)
a:1
b:2
c:3
2、判断指定键值是否存在
d = {'key1':'haha','key2':'haha2'}
'key_use' in d.keys()
3、将键转为列表
d = {'key1':'haha','key2':'haha2'}
list_keys = list(d.keys())
字符串
- replace() 将old字符 替换为 new字符
str.replace(old, new)
- join() 将序列中的元素以指定的字符连接生成一个新的字符串
s1 = "-"
seq = ("r", "u", "n", "o", "o", "b")
print(s1.join(seq))
>> r-u-n-o-o-b
- 以...开头或结尾
>>> item = "demo.mp4"
>>> item.endswith('.mp4')
True
>>> item.endswith('.json')
False
>>> item.startswith('demo')
True
>>> item.startswith('index')
False
>>>
- rfind()
返回字符串最后一次出现的位置,没有匹配成功返回-1
str.rfind(str,beg=0,end=len(string)
str = "this is really a string example....wow!!!";
substr = "is";
print str.rfind(substr);
#结果如下
5
集合set()
set()创建一个无序不重复元素集,可进行关系测试,删除重复数据等
class set([iterable])
>>>x = set('runood')
{'d', 'r', 'u', 'n', 'o'}