Python:对于列表中的每个元组,检查字符串是否在元组中

标签 python list tuples

我知道如何循环遍历列表中的所有元组。但是,我的问题是查看字符串是否在列表中的元组中。我构建了以下内容:

# 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 那么打印 “未找到日期”?

最佳答案

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] 也很有趣。如果您只需要知道日期是否存在,请使用any() 和生成器表达式来测试 匹配元素:

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 匹配了,但这实际上并不重要。

关于Python:对于列表中的每个元组,检查字符串是否在元组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30788248/

相关文章:

scala - 在Scala中,有没有一种简单的方法将案例类转换为元组?

python - 在Python中返回数字符号的奇怪语法

python - 我怎样才能停止PythonShell

python:模块 'Crypto.Cipher.AES' 没有属性 'MODE_CCM',即使安装了 pycrypto

python - 过滤掉 odoo 类型中选定的值

翻转列表/元组的pythonic方式

python - python中类变量的继承

python - arr[ :] in assignment in numpy? 是什么意思

python - 在空字典中连接元组

scala 新手遇到元组和闭包问题