【解決方法】リスト内の文字を検索して置換するにはどうすればよいですか?


Essentailly, my program is supposed generate a list, then have the user input a character they want to replace and a character they want to replace it with. This issue is that my functions for these processes just straight up aren't working.

import random

MAX_ELEMENTS = 25





MIN_CHAR = 33
MAX_CHAR = 126


# args(none)
# return(a randomly generated character) from ! to ~
def generateElement():
    # Declare variables for function
    aChar = " "
    dieRoll = -1

    dieRoll = random.randrange(MIN_CHAR, (MAX_CHAR + 1))
    aChar = chr(dieRoll)  # Function to convert ASCII code to a character
    return aChar


# args(none)
# Creates a list of 1 - 100 elements each element a string of length 1
# return (reference to the list)
def createList():
    # Declare variables for function
    global aList
    aList = []
    size = -1
    i = -1

    size = random.randrange(1, (MAX_ELEMENTS + 1))
    i = 0
    while i < size:
        aList.append(generateElement())
        i = i + 1
    return aList, size


# args(none)
# displays an index followed by each list element on it's own line
# return(nothing)
def display(aList, size):
    # Declare variables for function
    i = -1

    i = 0
    while i < size:
        print("Element at index[%d]=%s" % (i, aList[i]))
        i = i + 1

    # Starting execution point for the program

class ReplacedCharacter:
    findChar = "&"

class ReplacingCharacter:
    replaceChar = "."

def getFindAndReplaceCharacters():
    ReplacedCharacter.findChar = input("Enter the character you want to find here (ONE character only):")
    ReplacingCharacter.replaceChar = input("Enter the character you want to replace here (ONE character only):")





def replace_values():
    for list in aList:
        new_list = aList.replace(ReplacedCharacter.findChar, ReplacingCharacter.replaceChar)
    aList.append(new_string)




def start():
    # Declare variables local to start
    aList = []
    size = -1

    aList, size = createList()
    display(aList, size)
    getFindAndReplaceCharacters()
    replace_values()
    display(aList, size)



start()

私が試したこと:

パラメータを移動しようとしましたが、別の機能を追加してトラブルシューティングを試みましたが、今のところうまくいきません。 私が得続けるのは、「aListが定義されていません」ということだけです。 私のコードの問題は何ですか??

解決策 1

問題が発生する場所を説明していないので、ここでいくつかの仮定を立てています

Python
def createList():
    # Declare variables for function
    global aList
    aList = []

あなたは宣言しています aList になる global 変数ですが、グローバル名前空間には存在しないため、他の関数から「見る」ことはできません。 また、一部の関数が入力および/または戻り値として使用するため、コードに一貫性がありません。

次の 2 つのオプションのいずれかがあります。
1.定義する aList の中に global 次のようにコードを変更して、名前空間を次のように変更します。

Python
MAX_CHAR = 126
aList = []

しかし、それはあなたが必要とすることを意味します global すべての関数で宣言します。

2.使用 aList すべての関数への入力パラメーターとして、およびそれを変更するすべての戻り値として。

また、 createList リストのサイズを返す必要はありません。 len() 組み込み関数。

コメント

タイトルとURLをコピーしました