无法在Python的打印中添加变量

时间:2009-06-25 22:41:32

标签: python

我的代码:

year=[51-52,53,55,56,58,59,60,61]
photo=[{70,72,73},{64,65,68},{79,80,81,82},{74,77,78},{60,61,62},{84,85,87},{57,58,59},{53,54,55,56}]

for i in range(7):
    print "<img src=\"http://files.getdropbox.com/u/100000/Akuja/",year,"/P10104",photo,".JPG\">"

我跑了,我得到了

File "/tmp/aku.py", line 2
    photo=[{70,72,73},{64,65,68},{79,80,81,82},{74,77,78},{60,61,62},{84,85,87},{57,58,59},{53,54,55,56}]
              ^
SyntaxError: invalid syntax

我想要以下输出

<img src="http://files.getdropbox.com/u/100000/Akuja/51-52/P1010470.JPG">
<img src="http://files.getdropbox.com/u/100000/Akuja/51-52/P1010472.JPG">
<img src="http://files.getdropbox.com/u/100000/Akuja/51-52/P1010473.JPG">

<img src="http://files.getdropbox.com/u/100000/Akuja/53/P1010464.JPG">
<img src="http://files.getdropbox.com/u/100000/Akuja/53/P1010465.JPG">
<img src="http://files.getdropbox.com/u/100000/Akuja/53/P1010468.JPG">

...

我也使用list的语法运行相同的代码失败     相片= {[70,72,73],...}

如何使Python代码正常工作?

3 个答案:

答案 0 :(得分:3)

大括号用于表示字典(关联数组)。您想使用方括号,表示列表。

此外,您可能不希望在第一行中使用51-52,因为它将评估为-1。您应该输入“51-52”以确保它是一个字符串。

然后要获得你想要的索引,你需要做年** [i] **而不是年份,这会打印出整个列表。

答案 1 :(得分:2)

所以这是您解决简单问题的简单方法

year=['51-52', '53', '55' , '56' , '58', '59', '60', '61']
photo=[[70,72,73], [64,65,68],[79,80,81,82],[74,77,78],[60,61,62],[84,85,87],[57,58,59],[53,54,55,56]]

for i in range(len(year)):
   for j in range(len(photo[i])):
       print '<img src=\"http://files.getdropbox.com/u/100000/Akuja/%s/P10104%s.JPG>' % (year[i], photo[i][j])

答案 2 :(得分:1)

由于你试图迭代多年并打印那一年的照片,我会这样做:

year=["51-52","53","55","56","58","59","60","61"]
photo=[(70,72,73),(64,65,68),(79,80,81,82),(74,77,78),(60,61,62),
       (84,85,87),(57,58,59),(53,54,55,56)]

# this dictionary will be generated with the code below
#photos = {
#    "51-52": (70,72,73),
#    "53": (64,65,68),
#    "55": (79,80,81,82),
#    "56": (74,77,78),
#    "58": (60,61,62),
#    "59": (84,85,87),
#    "60": (57,58,59),
#    "61": (53,54,55,56)
#}


photos = {}                         # create photos dictionary

for y in xrange(len(year)):
    photos[year[y]] = photo[y]

years = photos.keys()               # sort the years
years.sort()

for year in years:
    for photo in photos[year]:
        print "<img src=\"http://files.getdropbox.com/u/100000/Akuja/"+year+"/P10104"+str(photo)+".JPG\">"

你得到:

<img src="http://files.getdropbox.com/u/100000/Akuja/51-52/P1010470.JPG">
<img src="http://files.getdropbox.com/u/100000/Akuja/51-52/P1010472.JPG">
<img src="http://files.getdropbox.com/u/100000/Akuja/51-52/P1010473.JPG">
<img src="http://files.getdropbox.com/u/100000/Akuja/53/P1010464.JPG">
<img src="http://files.getdropbox.com/u/100000/Akuja/53/P1010465.JPG">
<img src="http://files.getdropbox.com/u/100000/Akuja/53/P1010468.JPG">

如上所示,我会将照片和年份存储在字典中,但是如果您在单独的列表中有多年和照片(如在您的问题中),您可以创建这样的照片,注意年份在引号中“”:

photos = {}

for y in xrange(len(year)):
    photos[year[y]] = photo[y]