需要帮助从列表和Python中的函数创建字典

时间:2017-10-06 19:46:12

标签: python list function dictionary

所以我不确定如何准确解释它,但如果你看一下这段代码,你可以提供帮助。

class tower:
    def __init__(self, name, namex, namey, x, y, width, height, nameimg):
        self.name = name
        self.namex = namex
        self.namey = namey
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.nameimg = nameimg

    def getname(self):
        return self.name
    def getnamex(self):
        return self.namex
    def getnamey(self):
        return self.namey
    def getx(self):
        return self.x
    def gety(self):
        return self.y
    def getwidth(self):
        return self.width
    def getheight(self):
        return self.height
    def getnameimg(self):
        return self.nameimg


background = tower("background", "backgroundx", "backgroundy", 0, 0, 1280, 720, backgroundImg)
ppsh = tower("ppsh", "ppshx", "ppshy", 1127, 140, 120, 40, ppshImg)
trenchgun = tower("trenchgun", "trenchgunx", "trenchguny", 1207, 140, 120, 27, trenchgunImg)
thompson = tower("thompson", "thompsonx", "thompsony", 1127, 120, 120, 39, thompsonImg)
colt = tower("colt", "coltx", "colty", 1, 1, 70, 46, coltImg)
mg = tower("mg", "mgx", "mgy", 1, 1, 135, 27, mgImg)

towers = [background, ppsh, trenchgun, thompson, colt, mg]

def game_loop():
    positions = {
        (background.getnamex()): (background.getx()),
        (background.getnamey()): (background.gety()),
        (ppsh.getnamex()): (ppsh.getx()),
        (ppsh.getnamey()): (ppsh.gety()),
        (trenchgun.getnamex()): (trenchgun.getx()),
        (trenchgun.getnamey()): (trenchgun.gety()),
        (thompson.getnamex()): (thompson.getx()), 
        (thompson.getnamey()): (thompson.gety()),
        (colt.getnamex()): (colt.getx()), 
        (colt.getnamey()): (colt.gety()),
        (mg.getnamex()): (mg.getx()), 
        (mg.getnamey()): (mg.gety()),
        }

如果你查看底部我想做到这一点,我不必每次写出一个新的行,而是从上面的列表中取出。以下是我的尝试。

towers = [background, ppsh, trenchgun, thompson, colt, mg]

def game_loop():
    for i in towers:
        positions = {
            (i.getnamex()): (i.getx()),
            (i.getnamey()): (i.gety()),
            }

如果有人能提供帮助,我将不胜感激,我现在​​已经坚持了一段时间。

1 个答案:

答案 0 :(得分:2)

您可以定义空字典并根据需要添加键值对

<div class="form-group">
    <%= form.label :university %>
    <%= form.select :university_id, options_for_select(University.all.map{ |uni| [uni.name, uni.id] }), {prompt: 'Please Select Your University'}, { class: "form-control" } %>
  </div>