繁体   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