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})