簡體   English   中英

如何使用迭代來提高效率?

[英]how can I use iteration to make this more efficient?

我是python的新手,我知道我可以使用迭代(例如for循環)使下面的代碼更簡潔,我只是不知道如何

這就是我到目前為止所擁有的

# Open file for reading
dataFileRead = open(filename, "r")

# Read file content into a list - to be completed - Part 1

SampleData = [line.rstrip('\n') for line in open(filename)]
print(SampleData)

variables = [mazeWidth, mazeHeight, aNumOfTreasures, aNumOfBombs, emptyCell, treasure, bomb, exitGate, boundary, boundarySide]
mazeWidth = SampleData[0]
mazeHeight = SampleData[1]
aNumOfTreasures = SampleData[2]
aNumOfBombs = SampleData[3]
emptyCell = SampleData[4]
treasure = SampleData[5]
bomb = SampleData[6]
mario = SampleData[7]
exitGate = SampleData[8]
boundary = SampleData[9]
boundarySide = SampleData[10]

任何輸入有幫助! 謝謝

您可以使用字典來保存變量的名稱和值,而不是使用單獨的變量:

variable_names = ['mazeWidth', 'mazeHeight', 'aNumOfTreasures', 'aNumOfBombs', 'emptyCell', 'treasure', 'bomb', 'exitGate', 'boundary', 'boundarySide']

variables = {
  name: SampleData[i] for i, name in enumerate(variable_names)
}

稍后,如果您想要變量exitGate的值,例如,您可以使用:

variables['exitGate']

對於作業,使用:

variables['exitGate'] = "some value"

但是,如果您想要單獨的變量,可以使用:

for i, name in enumerate(variable_names):
    globals()[name] = SampleData[i]

之后您可以像往常一樣訪問(獲取和設置)變量( print(exitGate); exitGate = "some value" )。

如果你真的需要這11個變量以他們自己的名字存在,那就棄絕了。 11行沒什么大不了的。

否則,繼續使用列表SampleData

如果我要使用你的方法(我不會 - 稍后會詳細介紹),我會按如下方式編輯你的代碼,使用zip()dict()SampleDatavariables結合起來。

# Open file for reading
dataFileRead = open(filename, "r")

# Read file content into a list - to be completed - Part 1

SampleData = [line.rstrip('\n') for line in open(filename)]
print(SampleData)

#previously known as variables
variable_names = ["mazeWidth", "mazeHeight", "aNumOfTreasures", "aNumOfBombs", "emptyCell", "treasure", "bomb", "exitGate", "boundary", "boundarySide"]

variables = dict(zip(variable_names, SampleData))
print(variables)

這會將兩個列表合並為一個字典。 這樣,如果你想獲得炸彈的數量或迷宮的寬度,你所要做的就是寫:

print(variables["aNumOfBombs"])

字典就像這樣有用。 但是,我會完全重做系統。 無論如何,當你從文件中讀取時,我認為你應該使用json模塊並以這種方式存儲數據。 上面的所有代碼看起來都像:

import json

with open(filename, "r") as var_file:
    variables = json.load(var_file)

唯一的區別是你如何構造你讀取的文件,而這看起來像這樣:

{
    "mazeWidth": 5,
    "mazeHeight": 10,
    "aNumOfTreasures": 4,
    "aNumOfBombs": 16,
    "emptyCell": "whatever",
    "treasure": true,
    "bomb": true,
    "exitGate": false,
    "boundary": "red",
    "boundarySide": "NW"
}

了解更多!

暫無
暫無

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

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