<p>列表理解:</p>
<p><strong>迭代给定列表中的每个元素,按<code>/</code>拆分<strong>元素,然后再按<code>/</code>将拆分结果的前两项连接起来</p>
<pre><code>>>> l
['6/03/15', '9/03/15', '10/03/15', '11/03/15', '12/03/15', '13/03/15', '16/03/15', '17/03/15', '18/03/15', '19/03/15']
>>> ["/".join(i.split("/")[:2]) for i in l ]
['6/03', '9/03', '10/03', '11/03', '12/03', '13/03', '16/03', '17/03', '18/03', '19/03']
</code></pre>
<hr/>
<p>关于您的代码:</p>
<p>您的代码:</p>
<pre><code>def changeDateLength(dateList):
#- Why first item from the list is consider? This will raise exception IndexError
# when input is empty list.
# So not need to this.
dateLength = dateList[0]
#- Yes correct need new list varable.
newList = []
for date in dateList:
#- We iterate item from the list.
# so do process on item . dateLength[0] means first character from the dateLength variable which length is always 1.
# 1 > 7 will return False.
if len(dateLength[0]) > 7:
shortDateLength = dateLength[:5]
else:
shortDateLength = dateLength[:4]
#= Raise NameError exception because shore is not define
newList.append(shore)
return newList
</code></pre>
<p>尝试:</p>
<pre><code>def changeDateLength(dateList):
newList = []
for date_item in dateList:
if len(date_item) > 7:
shortDateLength = date_item[:5]
else:
shortDateLength = date_item[:4]
newList.append(shortDateLength)
return newList
dateList = ['6/03/15', '9/03/15', '10/03/15', '11/03/15', '12/03/15', '13/03/15', '16/03/15', '17/03/15', '18/03/15', '19/03/15']
new_dateList = changeDateLength(dateList)
print "new_dateList:", new_dateList
</code></pre>