需要python列表操作的帮助吗
我有两个单独的清单需要python列表操作的帮助吗,python,list,Python,List,我有两个单独的清单 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 = ["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个小时里,我们尝试了很多组合,但没有什么好结果:(这应该可以:
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))
在我之前指出了一些细节。在Python2.6中,我建议使用比编写简单类更少的代码和非常节省的内存使用:
import collections
Unit = collections.namedtuple('Unit', 'amount name')
units = [Unit(a, n) for a, n in zip(list2, list1)]
当一个类有一个固定的字段集(不需要它的实例每一个实例都具有可扩展性)和没有特定的“行为”(即,没有特定的方法)时,考虑使用一个命名的元组类型来代替(唉,在Python 2.5或更早的时候不可用,如果你被它所困扰的话)。
units = dict(zip(list1,list2))
for type,amount in units.iteritems():
print amount,type
无休止地扩展以获取更多信息,并且易于操作。如果基本类型可以完成这项工作,请仔细考虑不要使用它。@Ignacio:这是一个稳定的版本,现在已经有一年多的时间了。现在仍然有运行2.5甚至2.4的企业Linux发行版,我相信观察者应该知道这一点版本要求,即使最终没有取消OP解决方案的资格。期望OP阅读文档(我应该链接文档)是否不合理至少要知道他们的版本是否落后于大多数用户?什么,我打败了Alex Martelli,得到了Python的答案?这是怎么发生的?我想我需要一分钟来清醒一下,确保现在不是2012年或2038年。@Roger,嘿,是的--我花了额外的时间提供了链接,仔细指出了2.6的依赖性,以避免Ignacio通常的whi关于它(它准时到达你的;-),等等,所以你的答案在我还在“飞行中”的时候到达了
import collections
Unit = collections.namedtuple('Unit', 'amount name')
units = [Unit(a, n) for a, n in zip(list2, list1)]
units = dict(zip(list1,list2))
for type,amount in units.iteritems():
print amount,type