Python中两个list取交集、并集、差集以及为字符串str添加、插入特定字符的操作总结

Python中两个list取交集、并集、差集以及为字符串str添加、插入特定字符的操作总结

Python中两个list取交集、并集、差集

  • list(set(list_a).intersection(set(list_b)))获取两个list的交集
  • list(set(list_a).union(set(list_b)))获取两个list的并集
  • list(set(list_a).difference(set(list_b)))获取两个list的差集

典型范例:

a=[2,3,4,5]
b=[2,5,8]
list(set(a).intersection(set(b)))  # 获取两个list的交集
>>>
[2, 5]
list(set(a).union(set(b)))   # 获取两个list的并集
>>>
[2, 3, 4, 5, 8]
list(set(a).difference(set(b)))   # 获取两个list的差集—— b中有而a中没有的 
>>>
[3, 4]

参考链接:python两个 list 获取交集,并集,差集的方法

为字符串str添加、插入特定字符的操作总结

字符串str添加特定字符的常见方法:

  1. 可以使用+号实现字符串的连接,用法示例为:'image0001' + '.jpg'
  2. 使用方法.join()来连接字符串,用法示例为:'.'.join(['image0001' , 'jpg'])

备注:
' '.join([a, b])是比较常见的用法。’ '是空字符,意味着在a, b之间加入空字符,也就是将a, b进行了连接。

字符串str插入特定字符的常见方法:

首先将字符串转换为列表,然后使用列表的.insert()方法来插入字符。 注意:.insert()方法不返回参数,直接在对原list进行修改。

备注:
.insert() 函数用于将指定对象插入列表的指定位置。。比如['a', 'b'].insert(1, 'c'),那么最后的输出就是`[‘a’, ‘c’, ‘b’]。

典型范例:

a = 'I love '
b = 'China'
str_list = list(a)
str_list.insert(len(a), b)
a_b = ''.join(str_list)

参考链接:Python3 List insert()方法

扫描二维码关注公众号,回复: 12679578 查看本文章

猜你喜欢

转载自blog.csdn.net/weixin_42782150/article/details/106939734