fi中for循环中的If语句

2024-04-20 14:14:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件data.txt

./path1
 * WITH LDLDLDLDLDLD                 *
  KDKDKDKDKD
  LDLDLDLDLDLDLDLD
  LDFLFLFLFLFLFLF
['-2.6993']
['-2.6983']
['-2.4490']
  LSLSLSLSLSL
['-2.6993']
['-2.6983']
['-2.4490']
  KKKGKGKGKGKGKGKG
['-79.7549']
  LDLDLDLDLDLDLDLDL
['-126.6208']
['-93.9881']
  KDKDKDKDKDKDKDKD
['-156.9296']
['-135.3548']
  LDLDLDLDDLDDLDLDLD
['-178.3941']
['-162.8602']
['-42.7064']
  KDKDKDKDKDLDLDLDLDLD
['-193.3335']
['-181.9782']
['-68.6555']

./path2
 * WITH DLLDLDLDLDLLDLD                 *
  LDLDLDLDLDLDLD
  BEBEBEBEBEBEL
  LSLSLSLSLSLSL
['-2.6993']
['-2.6983']
['-2.4490']
  OSOSOSOSOSOSOSOS
['-2.6993']
['-2.6983']
['-2.4490']
  KDKDKDKDKDKDKDKDKD
['-156.9296']
['-135.3548']
  MDMDMDMDMDMDDMDM
['-178.3941']
['-162.8602']
['-42.7064']
  KFKFKFKFPKLDLDLD
['-193.3335']
['-181.9782']
['-105.4751']
['-96.2342']

我想从中打印path和该路径上的负值。你知道吗

以下代码实现了此目标:

import re
import os
import numpy as np

f = open('data.txt', 'r')
All_aux = []

for line in f:
         if re.match(r"^\.", line):
          print line

         if re.match(r"^\[", line):

                 target2 = line.translate(None, "[]'',")    
                 aux = target2.split()
                 All_aux.append(aux)
                 flat_list = [item for sublist in All_aux for item in sublist]

print 'len(negatives) = ' , len(flat_list)

但打印的信息如下:

./path1

./path2

len(negatives) =  32

一旦第一个if re.match(r"^\.", line):匹配,它就打印行,但不打印前17个负值。相反,该值将被保存并与第二条路径上的15个负值相加。你知道吗

我想获得以下信息:

./path1

len(negatives) =  17

./path2

len(negatives) =  15

有办法做到这一点吗?你知道吗


Tags: inimportrefordatalenifmatch
1条回答
网友
1楼 · 发布于 2024-04-20 14:14:33

这就是我所说的评论。我还做了一些其他的改进,例如使用一个字符串方法,它通常比正则表达式更简单、更有效。你知道吗

在与@tripleee进行了一些思考和讨论之后,我省去了flat_list,因为您所做的只是计算长度。你知道吗

我已经评论过了,但是如果你什么都不懂,请问:

# None of the imports are required
# We only need a count
negatives = 0

# Previously you were not closing the file
# This closes it automagically
with open('data.txt', 'r') as f:
    for line in f:
        # No need for a regular expression here
        if line.startswith("./"):
            if negatives:
                print 'len(negatives) = ' , negatives, '\n'
                negatives = 0
            print line

        # Used "else if" since both `startswith` can't be true
        elif line.startswith("["):
            target2 = line.translate(None, "[]'',")
            # simplified
            negatives += len(target2.split())

if negatives:
    print 'len(negatives) = ' , negatives

这将提供:

./path1

len(negatives) =  17

./path2

len(negatives) =  15

相关问题 更多 >