栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python in 字符串列表 部分匹配

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python in 字符串列表 部分匹配

word="hello"
word_list="hello world"
if word in word_list:
	print("True")
else:
	print("False")
	
result:True

word="hello"
word_list=["hello world","today is sunny","happy new year"]
if word in word_list:
	print("True")
else:
	print("False")
	
# result:False

word="hello"
word_list=["hello","today is sunny","happy new year"]
if word in word_list:
	print("True")
else:
	print("False")

# result:True

结论:
in 字符串匹配时,为部分匹配
in 列表匹配时,为完全匹配

如何对列表中的对象进行部分匹配呢

word="hello"
word_list=["hello world","today is sunny","happy new year"]

# 方案1
result=[]
for text in str1:
	if str in text:
		result.append(text)

# 方案2
result = [v for v in word_list if word in v]

# 方案3 
result=list(filter(lambda x: word in x, word_list))

#大小写转换
l = list(map(str.lower, l)) 映射字符串列表为小写
word1=word.lower(),word1小写 但word不变
	
# result:a=["hello world"]

查找列表中的重复元素并统计重复数量(python)
这个方法主要是用到collections.Counter函数,导入方法为from collections import Counter。collections在python官方文档中的解释是High-performance container datatypes,具体到Counter我认为可以理解为一个计数器,统计列表中的各个元素的个数。如果想详细了解Counter函数,可以参见这个链接:

Counter函数简介

from collections import Counter
ex = [1, 1, 3, 4, 4, 6]
result = dict(Counter(ex))
print(result)
print ([key for key,value in result.items() if value > 1]) 
print ({key:value for key,value in result.items() if value > 1}) 
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/846596.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号