Python:创建两个范围并连接到一个表达式

时间:2015-07-08 17:37:24

标签: python range

我想在Python中创建一个列表,列出一个年份(1996 - 2015年)的一个值和一个数字范围(1 - 200)。我像这样单独生成这些值:

souyear = []
sounumber = []

for y in range(1996, 2015):
    souyear.append(y)

for n in range(0,200):
    sounumber.append(n)

现在我想把这些值用分号分隔,1996:1,1996:2,1996:3等等到1996:200,然后转到1997:1,1997:2。这与仅合并两个列表不同,它要求每年生成200个数字。

1 个答案:

答案 0 :(得分:0)

使用zip和string方法获得结果

<强>演示

>>> years = range(1996, 2015)
>>> numbers = range(0,200)
>>> zip(years,numbers)
[(1996, 0), (1997, 1), (1998, 2), (1999, 3), (2000, 4), (2001, 5), (2002, 6), (2003, 7), (2004, 8), (2005, 9), (2006, 10), (2007, 11), (2008, 12), (2009, 13), (2010, 14), (2011, 15), (2012, 16), (2013, 17), (2014, 18)]
>>> result = ""
>>> for y, n in zip(years,numbers):
...     result += "%d:%d, "%(y, n)
... 
>>> result
'1996:0, 1997:1, 1998:2, 1999:3, 2000:4, 2001:5, 2002:6, 2003:7, 2004:8, 2005:9, 2006:10, 2007:11, 2008:12, 2009:13, 2010:14, 2011:15, 2012:16, 2013:17, 2014:18, '
>>> 

<强> DEMO2:

>>> import itertools
>>> years = range(1996, 2000)
>>> numbers = range(1,10)
>>> result = ""
>>> for year in years:
...     for y, n in itertools.product([year], numbers):
...         result += "%s:%s, "%(y, n)
... 
>>> result
'1996:1, 1996:2, 1996:3, 1996:4, 1996:5, 1996:6, 1996:7, 1996:8, 1996:9, 1997:1, 1997:2, 1997:3, 1997:4, 1997:5, 1997:6, 1997:7, 1997:8, 1997:9, 1998:1, 1998:2, 1998:3, 1998:4, 1998:5, 1998:6, 1998:7, 1998:8, 1998:9, 1999:1, 1999:2, 1999:3, 1999:4, 1999:5, 1999:6, 1999:7, 1999:8, 1999:9, '
>>>