需要帮助处理Python列表

0 投票
5 回答
574 浏览
提问于 2025-04-15 18:04

我有两个独立的列表

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  

所以我的目标是把list1和list2结合成一个可以方便调用的类。

我这3个小时尝试了很多组合,但都没有什么好的结果 :(

5 个回答

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 在我之前提到了一些细节。

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

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

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

撰写回答