![](/img/trans.png)
[英]Python: how to replace an element in a list with all elements from another list?
[英]How to replace all elements in list 1 with all elements from list 2 in defined function Python3
我有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()
这是预期的结果( 虽然不是全部结果 )
您会看到我的函数确实为第一个“样本字符串”显示了正确的结果,但是现在我应该继续处理其余元素(第二个样本“再见”的实际结果,依此类推)。
我不确定您到底想做什么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)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.