2010-01-15 64 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 

無休止擴張的其他信息,以及操控自如。如果一個基本類型可以完成這項工作,請仔細考慮不使用它。