【问题标题】:Iterating through all lines with multiple conditions遍历具有多个条件的所有行
【发布时间】:2018-11-11 08:55:28
【问题描述】:

我想一次遍历所有行并检查字符串是否在任何行中,如果是则应用函数并跳出循环,如果不是则检查第二个字符串并执行相同操作事物。如果在任何行中都没有找到字符串,则继续使用 else..

split= text.as_string().splitlines()
for row in split:
   if 'Thanks Friend' in row.any():
     apply_some_function()
     break
   elif 'other text' in row.str.any():
     apply_some_function()
     break
   else:
     .......

我不断收到错误:


AttributeError                            Traceback (most recent call last)
      <ipython-input-179-8f0e09f62771> in <module>()
      1 for row in split:
      2 
----> 3   if 'Thanks Friend' in row.str.any():
      4     apply_some_function()
      5     break

AttributeError: 'str' object has no attribute 'str'

【问题讨论】:

  • 怎么做,上面的代码不起作用,不断出现AttributeError: 'str' object has no attribute 'str'
  • 好吧,我猜你是Java背景的。在 Python 中,你可以做的事情更简单。这只是:if 'Thanks Friend' in row: elif 'other text' in row: ,如果我没记错的话。
  • 我想为每个条件一次遍历所有行,而不是一次一个

标签: python loops split line


【解决方案1】:

试试下面的。但请记住,文本将在回车符处拆分,这可能不是您想要做的。另外,如果“其他文本”被拆分,您是否想做一些不同的事情?如果你这样做了,那么你需要告诉我们。

split = text.split("\n")
if any(x for x in split if 'Thanks Friend' in x):
    apply_some_function()
elif any(x for x in split if 'other text' in x):
    apply_some_function()
else:
    pass

你也可以这样做:

if any(x for x in split if 'Thanks Friend' in x) or \:
any(x for x in split if 'other text' in x):
    apply_some_function()

【讨论】:

  • split 已经是一个列表,不,如果其他文本正在拆分,我希望应用相同的功能,如果满足前两个条件中的任何一个,我想跳出循环,即希望整个迭代结束。
  • 这可行,但即使在满足条件后它也会继续运行,有没有办法在它第一次返回为真时跳出循环?
  • 上面的代码中没有循环,所以我看不出它是如何继续运行的。
【解决方案2】:

您正在使用 python 中不存在的对象的属性/方法。这就是AttributeError 的意思。

查找对象所有现有属性的一种方法是在 python 控制台中使用函数help()。例如,键入 help(str) 以获取可用于字符串的所有方法。

当您想在每条线路上做不同的事情时,我认为没有办法“一次”转到所有线路。因此,您必须保留原始代码。这是它的固定版本:

split = text.splitlines()
for row in split:
    if 'Thanks Friend' in row:
        apply_some_function()
        break
    elif 'other text' in row:
        apply_some_function()
     break
   else:
       ...

【讨论】:

    猜你喜欢
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    • 2019-10-22
    • 2017-09-11
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多