python - 给定两个句子 S1,S2 ;任务是在 S1 中而不是在 S2 中查找单词
问题描述
问题陈述:-给定两个句子S1,S2;任务是在 S1 中而不是在 S2 中查找单词
def string_features(s, f):
s=s.lower()
s1=set(s.split())
f=f.lower()
s2=set(f.split())
s4=s1-s2
s4_list=list(s4)
s5=s2-s1
s5_list=list(s5)
for i in s4_list:
if i.upper() in s:
s4_list.remove(i)
s4_list.append(i.upper())
print(f"Words in S1 but not in S2 are : {s4_list}")
string_features(s="the first column F will contain only 5 uniques values",
f="the second column S will contain only 3 uniques values")
有了这个,我的预期输出应该是 ['first','F','5']; 但我得到['f','first','5']。'f' 仍然是小写字母,而它应该是大写字母'F'。
解决方案
lower()
当你想要区分大小写的结果时为什么要打电话?您在开头将整个字符串小写,然后 s 中没有大写字母,这使您的代码的最后一部分无用。实际上,只需删除即可lower()
使您的代码正常工作。
由于set是无序集合,如果您想保留阅读顺序,您可能需要使用 for 循环来迭代字符串或使用列表推导来完成。
def string_diff(s1, s2):
diff = list(set(s1.split()) - set(s2.split()))
diff2 = [c1 for c1 in s1.split() if c1 not in s2.split()]
print(f"Words in S1 but not in S2 are : {diff}")
print(f"Words in S1 but not in S2 are : {diff2}")
s1 = "the first column F will contain only 5 uniques values"
s2 = "the second column S will contain only 3 uniques values"
string_diff(s1, s2)
输出:
Words in S1 but not in S2 are : ['5', 'first', 'F']
Words in S1 but not in S2 are : ['first', 'F', '5']
推荐阅读
- reactjs - 使用反应从另一个组件中的一个组件获取更新的值
- ansible - Ansible 中的嵌套循环
- reactjs - 在将被迭代的组件(如列表项)中使用“makeStyles”有什么成本吗?
- xamarin - 如何将 ByteArray 从本机 iOS 库导出到 Xamarin 绑定库?
- julia - Julia 中的 Mapreduce 和带 sum 的过滤器有什么区别?
- keras - LSTM中记忆单元与时间步长的关系
- python - 为什么 add 函数会中断我的 while 循环?
- kotlin - 抛弃 Kotlin 箭头中的嵌套选项
- ruby - 如何避免两次打印输出
- python - 如何修复此错误:TypeError: cannot unpack non-iterable int object