2010-01-15 112 views
0

我有两个单独的列表学习Python列表操作帮助

list1 = ["Infantry","Tanks","Jets"] 
list2 = [ 10, 20, 30] 

因此在现实中,我有10个步兵,20辆坦克和30个喷气机

我想创建一个类,以便在年底,我可以称之为:

for unit in units: 
    print unit.amount 
    print unit.name 

#and it will produce: 
# 10 Infantry 
# 20 Tanks 
# 30 Jets 

因此我们的目标是要排序的组合列表1和列表2成可以很容易地调用的类。

一直在努力,在过去3个小时多的组合,没有什么好证明:(

回答

5

这应做到:

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)) 
+0

'units.add(...)'? – 2010-01-15 16:09:28

+0

@Dominic:哎呀,对不起。修正了,谢谢。 – unwind 2010-01-15 16:10:55

+1

一个更好的列表理解 – Claudiu 2010-01-15 16:50:52

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)] 
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) 

Alex指出一些细节我之前可以。

+1

只有Python 2.6+。 – 2010-01-15 16:16:52

+3

@Ignacio:这是一年以上的稳定版本。 – SilentGhost 2010-01-15 16:17:25

+1

现在仍然有Enterprise Linux发行版本运行2.5甚至2.4版,我相信观察者应该知道版本要求,即使它不会终止关于OP的解决方案。 – 2010-01-15 16:23:15

5

在Python 2.6中,我建议使用named tuple - les S码比编写简单的类并在内存中使用过很节俭:

import collections 

Unit = collections.namedtuple('Unit', 'amount name') 

units = [Unit(a, n) for a, n in zip(list2, list1)] 

当一个类有一个固定的字段(不需要它的实例是“扩张”与新的任意字段per-实例),没有特定的“行为”(即没有具体的必要方法),可以考虑使用一个命名的元组类型(alas,如果你坚持使用它,那么在Python 2.5或更低版本中不可用)。

+1

什么,我击败了Alex Martelli来Python的答案?这怎么发生的?我想我需要一分钟来清醒,并确保它不是2012年或2038年。 – 2010-01-15 16:20:09

+0

@Roger,heh,yep - 我花了额外的时间来提供链接,要小心指出2.6的依赖关系,以避免Ignacio通常对它的抱怨(准时到达你的;-)等等,所以你的答案到了我的还在“飞行中”;-)。 – 2010-01-15 16:40:01

2

怎么样词典:

units = dict(zip(list1,list2)) 

for type,amount in units.iteritems(): 
    print amount,type 

无休止扩张的其他信息,以及操控自如。如果一个基本类型可以完成这项工作,请仔细考虑不使用它。