Need help with python list manipulation
i have two seperate lists
list1 = ["Infantry","Tanks","Jets"]
list2 = [ 10, 20, 30]
so in reality, I have 10 Infantry, 20 Tanks and 30 Jets
I want to create a class so that in the end, I can call t开发者_开发问答his:
for unit in units:
print unit.amount
print unit.name
#and it will produce:
# 10 Infantry
# 20 Tanks
# 30 Jets
so the goal is to sort of combine list1 and list2 into a class that can be easily called.
been trying many combinations for the past 3 hrs, nothing good turned out :(
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)]
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)
Alex pointed out a few details before I could.
This should do it:
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))
In Python 2.6, I'd recommend a named tuple -- less code than writing the simple class out and very frugal in memory use too:
import collections
Unit = collections.namedtuple('Unit', 'amount name')
units = [Unit(a, n) for a, n in zip(list2, list1)]
When a class has a fixed set of fields (doesn't need its instances to be "expandable" with new arbitrary fields per-instance) and no specific "behavior" (i.e., no specific methods necessary), consider using a named tuple type instead (alas, not available in Python 2.5 or earlier, if you're stuck with that;-).
How about a dictionary:
units = dict(zip(list1,list2))
for type,amount in units.iteritems():
print amount,type
Endlessly expandable for additional information, and easily manipulated. If a basic type will do the job, think carefully about not using it.
精彩评论