python - 想在相同的比赛后打印额外的字符,在这种情况下只有“s”
问题描述
仅在匹配后从以下字符串中打印's',例如: things 和 night 具有相同的字符串和 s 是额外的,需要打印到控制台
s1 = 'things'
s1 = sorted(s1)
s2 = 'night'
s2 = sorted(s2)
l1 = len(s1)
l2 = len(s2)
max_len = max(l1,l2)
# max_len = list(map(int, str(max_len)))
if s1[0:] != s2[0:]:
for i in range(max_len):
if s1[i] == s2[i]:
print(s1[i])
预期输出:=s
解决方案
您可以做一些Counter
不同的事情来获取任一字符串中但不在另一个字符串中的所有字符:
from collections import Counter
def diff(s1, s2):
c1, c2 = Counter(s1), Counter(s2)
return "".join(((c1-c2) + (c2-c1)).elements())
diff("things", "night")
# 's'
diff("abcd", "cdef")
# 'abef'
一种更简单的方法,使用生成器:
def diff(s1, s2):
for c in s1:
if c not in s2:
yield c
for c in s2:
if c not in s1:
yield c
[*diff("things", "night")]
# ['s']
[*diff("abcd", "cdef")]
# ['a', 'b', 'e', 'f']
然而,这将忽略相同字符的不同计数。
推荐阅读
- c - 如何用一个字符替换两个字符?
- sql - Sql ER图:产品与父母关系
- python - 如何使用python获得给定显着性水平的拒绝区域
- excel - 使用 VBA 自动过滤列时如何仅包含特定单词
- c - 检查用户是否根据格式输入
- python - TensorFlow:设计自定义层时 __call__() 和 call() 的功能之间的区别?
- c++ - 为什么函数二返回 cout << s << " " << t << " " << b << endl; 当它说只返回(b)时?
- python - 如何解决 FieldError - 无法将关键字“slug”解析为字段
- mysql - DUPLICATE KEY UPDATE 只能工作一次?
- android - 为什么我的搜索栏没有隐藏提示“搜索...”?