我正在尝试使用for循环遍历元组列表的第一个元素。
for i in link_list:
print 'http://www.newyorksocialdiary.com%s' % link_list[i][0]
然而,我收到此错误:
TypeError Traceback (most recent call last)
<ipython-input-72-8c0e1be937a4> in <module>()
1 for i in link_list:
----> 2 print 'http://www.newyorksocialdiary.com%s' % link_list[i][0]
TypeError: list indices must be integers, not tuple
如何遍历元组列表并仅打印第一个元素,例如:
'http://www.newyorksocialdiary.com/party-pictures/2014/the-thanksgiving-day-parade-from-the-ground-up'
'http://www.newyorksocialdiary.com/party-pictures/2014/gala-guests'
如果有帮助,这就是link_list的样子:
[('/party-pictures/2014/the-thanksgiving-day-parade-from-the-ground-up',
datetime.datetime(2014, 12, 1, 0, 0)),
('/party-pictures/2014/gala-guests', datetime.datetime(2014, 11, 24, 0, 0)),
('/party-pictures/2014/equal-justice', datetime.datetime(2014, 11, 20, 0, 0)),
('/party-pictures/2014/celebrating-the-treasures',
datetime.datetime(2014, 11, 18, 0, 0)),
('/party-pictures/2014/associates-and-friends',
datetime.datetime(2014, 11, 17, 0, 0))]
答案 0 :(得分:0)
您误解了循环在Python中的工作方式。 i
不是索引,它是元素本身。您应该使用% i[0]
。
答案 1 :(得分:0)
你可以这样做:
for i in link_list:
print 'http://www.newyorksocialdiary.com%s' % i[0]
或者由于其他原因需要实际索引:
for i in range(len(link_list)):
print 'http://www.newyorksocialdiary.com%s' % link_list[i][0]
执行for i in link_list
时,i
是列表的元素,而不是索引。