簡體   English   中英

遍歷列表並替換 Python 中的字符串

[英]Going through a list and replacing a string in Python

我是 python 的新手,想為我的基於文本的游戲創建一個簡單的庫存 function。 我希望通過列表(庫存)將 function 到 go 並用一個項目替換標題為“空”的第一行。

這是我所擁有的:

Inventory =["Empty", "Empty", "Empty", "Empty", "Empty", "Empty", "Empty", "Empty", "Empty"]

def inventory(item):
    for line in Inventory:

我知道的不多。 所以基本上當我在 function 中輸入“項目”時,我想要 function 到 go 通過列表替換第一個“Empty”,然后用“停止”字符串替換它希望這不是一個太模糊的問題。

為此,您可以說:

Inventory = ["Empty", "Empty", "Empty", "Empty", "Empty", "Empty", "Empty", "Empty", "Empty"]
def inventory(item): 
   for i in range(len(Inventory)): 
       if Inventory[i] == 'Empty': 
          Inventory[i] = item 
          break; 

或者,您可以在一行中執行此操作並說:

def inventory(item): 
    if 'Empty' in Inventory: 
       firstEmptyIndex = Inventory.index('Empty')
       Inventory[firstEmptyIndex]  = item 

沒有必要為此使用循環。

try:
    empty_pos = Inventory.index("Empty")
except ValueError:
    print("No empty slots!")
else: 
    Inventory[empty_pos] = item

我認為最好修改列表而不將其傳遞給不返回 function。 這涉及到 python 可變變量引用scope

本質上,您可能認為可以將列表傳遞到 function 並在 function 內更改其值,但在 function 之外它應該保持不變。 然而,這不是 python 列表的工作方式。

例如:

def temp(data):
    data.clear()

data1 = [1,2,3]
temp(data1)
print(data1) 

# output:
[] 

The short version is that python variables are refered by their id, and passing a list as-is (just passing the name, as example show) into a function means that now list inside the function and outside the function shares same id, which means在 function 中進行的修改將影響 function 之外的列表。 (當您將列表傳遞到多個不同的 function 時,行為相同,現在每個 function 都在修改該列表)

此外,根據您修改列表的方式,有時會生成新的 id,這會更加混亂邏輯。

我認為最好的方法是傳遞原始列表的副本(以便 function 使用具有相同值但不同 id 的列表,這意味着所有修改都不會反映到原始列表),並讓 function 返回新列表。 然后將新的回報分配給您的變量

附言。 傳遞列表的副本意味着您正在復制價值並獲取更多的 memory,但除非您有 1GB 列表,否則它實際上並不那么重要。 如果是這樣,將其傳入 without.copy() 並使用 function 返回的新值也可以。

def process_list(data):
    # code provided by other answers 
    return data 

inventory = process_list(inventory.copy())

這樣可以更清楚地了解值是如何改變的

這是假設庫存中至少有一個“空”字符串的代碼

Inventory = ["Empty", "Empty", "Empty", "Empty", "Empty", "Empty", "Empty", "Empty", "Empty"]
def inventory(item):
    Inventory[Inventory.index("Empty")] = item

無需假設

Inventory = ["Empty", "Empty", "Empty", "Empty", "Empty", "Empty", "Empty", "Empty", "Empty"]
def inventory(item):
    try:
        Inventory[Inventory.index("Empty")] = item
    except ValueError:
        pass # since you didn't mention what to do if "Empty" does not exist

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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