我有2个列表和准备好的传递和打印功能。我可以分别用第二个列表的每个元素替换第一个列表的每个元素,但我不知道如何在函数中一起完成。我现在已经在stackoverflow上搜索了几个小时的答案,但是这个主题上的所有python东西都很老了,与python 3.6不兼容。我希望您可以在不使用任何导入方法的情况下(例如if / elif或其他方法)给我一个提示。以下是我到目前为止的情况:
def goodbadString(string):
for (a,b) in zip(strings, expectedResults):
string = string.replace(strings[0],expectedResults[0])
return string
strings = ['It has been a good and bad day', 'bad company',
'good is as good does!', 'Clovis is a big city.']
expectedResults = ['I am confused', 'goodbye', 'hello',
'hello and goodbye']
for string, expectedResult in zip(strings, expectedResults):
print('Sample string = ', string)
print('Expected result =', expectedResult)
print('Actual result =', goodbadString(string))
print()
这是预期的结果(虽然不是整个结果)
你可以看到我的功能确实显示了第一个"样本字符串"但是现在我应该继续其余的元素(第二个样本的实际结果"再见"依此类推)。
答案 0 :(得分:2)
我不确定你想要goodbadString()
做什么。这是一次尝试:
def goodbadString(string):
idx = strings.index(string)
return string.replace(strings[idx],expectedResults[idx])
Sample string = It has been a good and bad day
Expected result = I am confused
Actual result = I am confused
Sample string = bad company
Expected result = goodbye
Actual result = goodbye
Sample string = good is as good does!
Expected result = hello
Actual result = hello
Sample string = Clovis is a big city.
Expected result = hello and goodbye
Actual result = hello and goodbye
这实际上是愚蠢的......只需返回预期的字符串而无需替换任何东西:
def goodbadString(string):
return expectedResults[strings.index(string)]