簡體   English   中英

如何在定義的函數Python3中用列表2中的所有元素替換列表1中的所有元素

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM