【问题标题】:Manipulate the output of if any for loop操作 if 循环的输出
【发布时间】:2018-11-09 12:35:58
【问题描述】:

我需要比较以下sequences 列表项:

sequences = ['sphere_v002_', 'sphere_v002_0240_', 'test_single_abc_f401']

到:

folder = 'sphere_v002'

然后处理包含folder 的列表项。

我有一个工作功能,但我想改进它。

当前代码是:

foundSeq = False

for seq in sequences:
    headName = os.path.splitext(seq.head())[0]

    #Check name added exception for when name has a last underscore                 
    if headName == folder or headName[:-1] == folder:
        foundSeq = True
        sequence = seq

if not foundSeq:
    ...

我的改进如下:

if any(folder in os.path.splitext(seq.head())[0] for seq in sequences):
    print seq

然后我收到以下错误:

local variable seq referenced before the assignment

如何使用改进的解决方案获得正确的输出?

【问题讨论】:

  • 也许使用filter函数..?

标签: python match any


【解决方案1】:

any 仅返回一个布尔值,当您的条件满足时,它不会将sequences 中的元素存储在变量seq 中。

您可以做的是使用生成器并利用 None 是“Falsy”这一事实:

def get_seq(sequences, folder):
    for seq in sequences:
        if folder in os.path.splitext(seq.head())[0]:
            yield seq

for seq in get_seq(sequences, folder):
    print seq

如果愿意,您可以将其重写为生成器表达式:

for seq in (i for i in sequences if folder in os.path.splitext(i.head())[0]):
    print seq

如果从未指定条件,则生成器或生成器表达式将不会产生任何值,并且不会处理循环中的逻辑。

【讨论】:

    【解决方案2】:

    正如 jpp 所指出的,any 只返回一个布尔值。因此,在这种特殊情况下,如果有的话不是好的解决方案。

    就像 thebjorn 建议的那样,迄今为止对我们来说最有效的代码在于使用filter 函数。

    sequences = ['sphere_v002_', 'sphere_v002_0240_', 'test_single_abc_f401']
    match = filter(lambda x: 'sphere_v002' == x[:-1] or 'sphere_v002' == x, sequences)
    print match
    ['sphere_v002_']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-23
      • 1970-01-01
      • 1970-01-01
      • 2019-05-05
      • 1970-01-01
      • 2018-01-22
      相关资源
      最近更新 更多