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

2024-10-03 19:22:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个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
...

我想我快到了,但还没完全明白。你知道吗

有人能帮忙吗?你知道吗

谢谢


Tags: and项目in密码列表for间隔错误
2条回答

如果两个列表长度相同,则还可以使用枚举:

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

您需要的是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)]

相关问题 更多 >