我知道如何遍历列表中的所有元组。但是,我的问题是查看字符串是否在列表中的元组中。我构建了以下内容:
# where:
unformatted_returns = [('2015-6-10', u'88.48'), ('2015-6-9', u'86.73'), ('2015-6-8', u'86.15'), ('2015-6-5', u'86.05')]
date_new = '2015-6-8'
for n in unformatted_returns: # The problem is here
if str(date_new) in n[0]:
print "found date"
rate_of_return_calc(date, date_new)
pass
else:
print "date {0} not found".format(date_new)
day_accumulater(d, m, y, date_new, date)
问题是循环n in unformatted_returns
中的第一个元组不满足条件,因此它打印“未找到”。我不希望它显然这样做,因为date_new
实际上在列表中!
那么,如何让程序在每个n
之间循环,如果所有n
都不满足包含date_new
,那么打印"day not found"
?
答案 0 :(得分:4)
将else
向下移动一级。 for
循环也会使用else
套件,当未提前退出循环时执行该套件。然后添加break
:
for n in unformatted_returns:
if date_new == n[0]:
print "found date"
rate_of_return_calc(date, date_new)
break
else:
print "date {0} not found".format(date_new)
day_accumulater(d, m, y, date_new, date)
我也清理了你的考试;您将n[0]
与日期字符串匹配,您希望它们相等,而不是一个是另一个的子字符串。
现在可能发生以下两种情况之一:
date_new
等于其中一个元组的第一个元素。执行break
,for
循环结束,并跳过else
套件。
date_new
不等于元组的任何第一个元素。永远不会执行break
,循环结束并执行else
套件以显示未找到匹配项。
演示:
>>> unformatted_returns = [('2015-6-10', u'88.48'), ('2015-6-9', u'86.73'), ('2015-6-8', u'86.15'), ('2015-6-5', u'86.05')]
>>> date_new = '2015-6-8'
>>> for n in unformatted_returns:
... if date_new == n[0]:
... print "found date"
... break
... else:
... print "date {0} not found".format(date_new)
...
found date
>>> date_new = '2015-6-7' # not in the list
>>> for n in unformatted_returns:
... if date_new == n[0]:
... print "found date"
... break
... else:
... print "date {0} not found".format(date_new)
...
date 2015-6-7 not found
这显然只会找到第一个这样的匹配元素。
如果必须处理所有匹配元素,则标记通常最简单:
found = False
for n in unformatted_returns:
if date_new == n[0]:
print "found date"
rate_of_return_calc(date, date_new)
found = True
if not found:
print "date {0} not found".format(date_new)
day_accumulater(d, m, y, date_new, date)
所有这些都假定n[1]
也是有意义的。如果你需要知道日期是否为 present ,请使用any()
和生成器表达式来测试 a 匹配元素:
if any(n[0] == date_new for n in unformatted_returns):
print "found date"
rate_of_return_calc(date, date_new)
else:
print "date {0} not found".format(date_new)
day_accumulater(d, m, y, date_new, date)
现在我们不知道哪个 n
匹配,但这实际上并不重要。
答案 1 :(得分:1)
只需使用标志:
unformatted_returns = [('2015-6-10', u'88.48'), ('2015-6-9', u'86.73'), ('2015-6-8', u'86.15'), ('2015-6-5', u'86.05')]
date_new = '2015-6-8'
found_one = False
for n in unformatted_returns: # The problem is here
if str(date_new) in n[0]:
print "found date"
rate_of_return_calc(date, date_new)
found_one = True
# add a break here if you are only interested in the first match
if not found_one:
print "date {0} not found".format(date_new)
day_accumulater(d, m, y, date_new, date)
答案 2 :(得分:1)
只搜索匹配项,如果搜索没有结果,则找不到任何内容:
matching_returns = [ur for ur in unformatted_returns if date_new == ur[0]]
if not matching_returns:
print "date {0} not found".format(date_new)
else:
# do something with matching_returns