如何在已定义函数Python3中将列表1中的所有元素替换为列表2中的所有元素

2024-05-19 00:24:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个列表和一个函数的现成的传递和打印。我可以将第一个列表的每个元素分别替换为第二个列表中的每个元素,但我不确定如何在一个函数中同时使用这些元素。我已经在stackoverflow上搜索了几个小时的答案,但是这里所有关于这个主题的python内容都太旧了,与python3.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()

这是预期结果(虽然不是整个结果)

enter image description here

对于我的第一个示例“再见”和“我应该继续”的第一个示例的结果。在


Tags: and方法函数in元素列表forstring
1条回答
网友
1楼 · 发布于 2024-05-19 00:24:20

我不知道你到底想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

这真是愚蠢。。。只需返回预期的字符串,而不必费心替换任何内容:

^{pr2}$

相关问题 更多 >

    热门问题