所以基本上,我需要遍历 s、s1 和 s2 中的每个 X 列表并识别第一个值,例如。 FOX 并替换为前 3 个字符串 [0, 1, 2] 中的“MONKEY”(大写)。我可以让所有其他字符串正常工作,但这些字符串在算法中会感到困惑。这是因为“fox”和“monkey”在字符串 X 的位置中的位置以及位置的变化,就像 .find() 忽略了它。
X = [ ["The fox chattered the dim monkey's ears off!", 'FOX' , 'MoNkEy' ],
["The fox chattered the dim monkey's ears off!", 'MoNkEy', 'FOX' ],
["The monkey chattered the dim fox's ears off!", 'FOX' , 'MoNkEy' ],
["Silly monkey chattered dim fox's ears off!" , 'siLLy' , 'dIm' ]]
def swap_strs(s, s1, s2):
if s1.upper() == '' or s1.upper() not in s.upper():
return "s1 NO GOOD"
if s2.upper() == '' or s2.upper() not in s.upper():
return "s2 NO GOOD"
l1, l2 = len(s1), len(s2)
slower = s.lower()
p1, p2 = slower.find(s1.lower()), slower.find(s2.lower())
s1 = s1.upper()
s2 = s2.upper()
target = s[:p1] + s2 + s[p1+len(s1):p2] +s1
return target
def Q1():
for s, s1, s2 in X:
print(s, '\n', swap_strs(s, s1, s2))
Q1()
目前我的结果代码是这样的,有什么建议吗?
Q1()
The fox chattered the dim monkey's ears off!
The MONKEY chattered the dim FOX
The fox chattered the dim monkey's ears off!
The fox chattered the dim FOXMONKEY
The monkey chattered the dim fox's ears off!
The monkey chattered the dim MONKEYFOX
Silly monkey chattered dim fox's ears off!
DIM monkey chattered SILLY
期望的输出:
Q1()
The fox chattered the dim monkey's ears off!
The MONKEY chattered the dim FOX's ears off!
The fox chattered the dim monkey's ears off!
The MONKEY chattered the dim FOX's ears off!
The monkey chattered the dim fox's ears off!
The FOX chattered the dim MONKEY's ears off!
Silly monkey chattered dim fox's ears off!
DIM monkey chattered SILLY fox's ears off!
最佳答案
您当前的方法似乎有点棘手:我确信一个人可以使其发挥作用,但似乎很难让所有细节都正确。直接使用 replace()
也无法解决这个问题。
我得到的关于编程的最好建议是创建智能数据结构,这样你的算法就可以是愚蠢的。下面是这个想法的一个例子:
TESTS = [
["The fox chattered the dim monkey's ears off!", 'FOX' , 'MoNkEy' ],
["The fox chattered the dim monkey's ears off!", 'MoNkEy', 'FOX' ],
["The monkey chattered the dim fox's ears off!", 'FOX' , 'MoNkEy' ],
["Silly monkey chattered dim fox's ears off!" , 'siLLy' , 'dIm' ]
]
def swap_strs(s, r1, r2):
# Normalized strings.
lows = s.lower()
low1 = r1.lower()
low2 = r2.lower()
# Create a pair of (POS, OLD, NEW) tuples.
replacements = [
(lows.find(low1), low1, r2.upper()),
(lows.find(low2), low2, r1.upper()),
]
# Sort on POS, reverse order so that we make replacements
# starting at end of string.
replacements.sort(reverse = True)
# Now the replacement logic (the algorithmic part) is very simple.
for p, old, new in replacements:
s = s[0:p] + new + s[p + len(old):]
return s
def main():
for s, r1, r2 in TESTS:
res = swap_strs(s, r1, r2)
print(s)
print(res)
print()
main()
关于python - 使用子字符串进行列表切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56213173/