打印两个列表的内容,以便按顺序从每个打印对应的记录

时间:2014-08-12 19:31:23

标签: python list

我有两个包含年份增量的Python列表,交错一年(一个运行1999-2013,另一个运行2000-2014)。我想打印这些,以便两个列表中的相应项目一个接一个地打印。这是我的代码:

list1 = [1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013]
list2 = [2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014]


for x in list1 and y in list2:
    print "list1 - " + str(x)
    print "list2 - " + str(y)

产生以下错误:

Traceback (most recent call last):
  File "C:\Python27\newtets\newtets\spiders\test3.py", line 12, in <module>
    for x in list1 and y in list2:
NameError: name 'y' is not defined

我已经尝试了各种旋转(以不同的组合嵌套语句,但它们都不工作或者不以我想要的格式生成输出,这将是):

list1 - 1999
list2 - 2000
list1 - 2000
list2 - 2001
list1 - 2001
list2 - 2002
...

我认为我几乎就在那里,但却无法得到它。

有人可以帮忙吗?

由于

2 个答案:

答案 0 :(得分:1)

你想要的是zip功能。

for x, y in zip(list, list2):
  print "list1 - " + str(x)
  print "list2 - " + str(y)

zip函数接受两个列表并将它们交错到元组列表中,如下所示:

>>> list1 = [1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013]
>>> list2 = [2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014]
>>> zip(list1,list2)
[(1999, 2000), (2000, 2001), (2001, 2002), (2002, 2003), (2003, 2004), (2004, 2005), (2005, 2006), (2006, 2007), (2007, 2008), (2008, 2009), (2009, 2010), (2010, 2011), (2011, 2012), (2012, 2013), (2013, 2014)]

答案 1 :(得分:1)

如果两个列表的长度相同,您也可以使用枚举:

for ind, ele in enumerate(list1): # ind is the index of each element in the list
    print "list1 {}\nlist2 {}".format(ele,list2[ind])
list1 1999
list2 2000
list1 2000
list2 2001
list1 2001
list2 2002

如果您有不同的尺寸列表,则可能需要itertools.izip_longest使用fillvalue填写缺失值。

list1 = [1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013]
list2 = [2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012]

from itertools import izip_longest

for ele1,ele2 in izip_longest(list1,list2,fillvalue="No corresponding data"):
    print "list1 {}\nlist2 {}".format(ele1,ele2)


list1 1999
list2 2000
list1 2000
list2 2001
list1 2001
list2 2002
list1 2002
list2 2003
list1 2003
list2 2004
list1 2004
list2 2005
list1 2005
list2 2006
list1 No corresponding data
list2 2007
list1 No corresponding data
list2 2008
list1 No corresponding data
list2 2009