我有两个单独的名单
list1 = ["Infantry","Tanks","Jets"]
list2 = [ 10, 20, 30]
Run Code Online (Sandbox Code Playgroud)
所以实际上,我有10个步兵,20个坦克和30个喷气机
我想创建一个类,以便最后,我可以这样称呼:
for unit in units:
print unit.amount
print unit.name
#and it will produce:
# 10 Infantry
# 20 Tanks
# 30 Jets
Run Code Online (Sandbox Code Playgroud)
所以我们的目标是将list1和list2组合成一个可以轻松调用的类.
在过去3小时内尝试了很多组合,没有什么好结果:(
Ign*_*ams 18
class Unit(object):
def __init__(self, amount, name):
self.amount = amount
self.name = name
units = [Unit(a, n) for (a, n) in zip(list2, list1)]
Run Code Online (Sandbox Code Playgroud)
小智 8
from collections import namedtuple
Unit = namedtuple("Unit", "name, amount")
units = [Unit(*v) for v in zip(list1, list2)]
for unit in units:
print "%4d %s" % (unit.amount, unit.name)
Run Code Online (Sandbox Code Playgroud)
亚历克斯在我可以之前指出了一些细节.
这应该这样做:
class Unit:
"""Very simple class to track a unit name, and an associated count."""
def __init__(self, name, amount):
self.name = name
self.amount = amount
# Pre-existing lists of types and amounts.
list1 = ["Infantry", "Tanks", "Jets"]
list2 = [ 10, 20, 30]
# Create a list of Unit objects, and initialize using
# pairs from the above lists.
units = []
for a, b in zip(list1, list2):
units.append(Unit(a, b))
Run Code Online (Sandbox Code Playgroud)
在Python 2.6中,我建议使用一个名为tuple的代码 - 比编写简单类更少的代码,并且在内存使用方面也非常节俭:
import collections
Unit = collections.namedtuple('Unit', 'amount name')
units = [Unit(a, n) for a, n in zip(list2, list1)]
Run Code Online (Sandbox Code Playgroud)
当一个类有一组固定的字段(不需要它的实例是"可扩展的",每个实例有新的任意字段)而没有特定的"行为"(即,没有必要的特定方法)时,考虑使用一个命名的元组类型相反(唉,在Python 2.5或更早版本中不可用,如果你坚持使用;-).