最近在做一些文本的处理,把用到的一些小细节记下来。
目录
3.把两个一维列表合并为二维列表,或者把两个字符串合并成一个列表
1.同时以多个分隔符切分字符串
如果说用一个固定的字符串切分的话,可能用 text.split("/")(这里text是字符串变量,/表示用"/"作为分割标准,返回的是切分后的列表),
list = "两只老虎,两只老虎。跑得快,跑得快。一直没有眼睛,一直没有尾巴。真奇怪,真奇怪"
list.split("。")
这里用空格作为分割符,此时的输出是:
['两只老虎,两只老虎', '跑得快,跑得快', '一直没有眼睛,一直没有尾巴', '真奇怪,真奇怪']
如果我们的目的是分成很短的句子,这样还不太行。当然我们再用句号分一次,但如果想一步,此时就要用到库 re 。re 通常在正则化匹配时会用到,我这里有点用牛刀的感觉,哈哈
import re
list = "两只老虎,两只老虎。跑得快,跑得快。一直没有眼睛,一直没有尾巴。真奇怪,真奇怪"
re.split(",|。", list)
此时的输出是
['两只老虎', '两只老虎', '跑得快', '跑得快', '一直没有眼睛', '一直没有尾巴', '真奇怪', '真奇怪']
2.删除列表最后一个元素的方法
- pop:list.pop()
- del的方法:del(list[-1])
- 切片:list = list[0:-1]
my_list = [1, 2, 3, 4, 5]
del(my_list[-1])
# 输出[1,2,3,4]
my_list = my_list[0:-1]
# 输出[1,2,3]
my_list.pop()
# 输出[1,2]
3.把两个一维列表合并为二维列表,或者把两个字符串合并成一个列表
都知道 python 可以通过 + 直接把两个列表合并,比如:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
long_list = list1 + list2
# 输出:[1, 2, 3, 4, 5, 6]
# 对于字符串
list1 = "abd"
list2 = "sfd"
long_list = list1 + list2
# 输出:'abdsfd'
但是,想把两个列表合并为二维列表怎么办呢,给相加的对象加个 [] 就好了,有点点意思呢:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
con_list = [list1] + [list2]
# 输出:[[1, 2, 3], [4, 5, 6]]
# 对于字符串
list1 = "abd"
list2 = "sfd"
con_list = [list1] + [list2]
# 输出:['abd', 'sfd']
4.查看列表是否为空
可能容易想到的是用 if list == [] 或者 if list == ""
list1 = []
if list1 != []:
print("list1 is not None")
else:
print("list1 is None")
# 输出:list1 is None
还有一种方式是用 if len(list) == 0
list1 = []
if len(list1) == 0:
print("list1 is None")
else:
print("list1 is not None")
# 输出:list1 is None
5.判断二维列表是否为空
在筛除空列表时,发现构造的一些二维空列表没有被剔除掉,猜测是一维空列表的判断方法对它不适用,去验证了一下,发现确实是这样。
my_list = [[]]
if my_list != []:
print("my_list is not None")
else:
print("my_list is None")
# 输出:my_list is not None
if len(my_list) == 0:
print("my_list is None")
else:
print("my_list is not None")
# 输出:my_list is not None
print(len(my_list))
# 输出:1
就是说,此时对于 [] 来说,内部有一个 [] 这样的空元素,那么判断就是 if list == [[]]
my_list = [[]]
if my_list != [[]]:
print("my_list is not None")
else:
print("my_list is None")
# 输出:my_list is not None