查找前一行的一部分是否等于Python中当前行的一部分

时间:2016-05-01 11:33:52

标签: python line equals

我对我的代码有疑问。如果前一行的特定部分等于当前行中的特定部分(在本例中为Z部分),我想返回True。我的文件看起来像这样:

        //adapter for list
    simpleAdapter = new SimpleAdapter(
            this,
            Splash.scriptList,
            R.layout.mytextview,
            new String[] {"value","key"},
            new int[] { android.R.id.text1,android.R.id.text2 });

所以在这种情况下,如果" Z"之后的值,我想要一个True。第2行中的(268.4040)等于第1行中的那部分。因此,这里的结果为True。一旦前一行中的值不等于当前行中的值,我想要一个False。所以第4行就是这种情况(328.5575不等于268.4040)。该文件名为" pointZ.gcode"并有很多行。任何人都可以帮我提供返回我想要的Python代码吗?谢谢!

到目前为止我的代码:

  G17 G3 X387.9385 Y200.0000 Z268.4040 R187.9385
  G17 G3 X200.0000 Y387.9385 Z268.4040 R187.9385
  G17 G3 X200.0000 Y387.9385 Z268.4040 R187.9385
  G17 G3 X200.0000 Y353.2089 Z328.5575 R153.2089

这给了我错误:IndexError:列表索引超出范围

2 个答案:

答案 0 :(得分:2)

我不会在这里发布代码,希望你试试。但是会给你提示:

1)Read the line from the file.
2) Split it on basis of " ".
3) The 4th element of the list is what you want. 
4) Now check it with previous string. You will need to maintain a variable where you will have to store the previous string. Initially it can be null. 
5) If it matches, print True else print False

答案 1 :(得分:1)

一种可能的解决方案,它不会从文件中读取,但会显示一个将结果累积到列表中的基本算法,列表的长度为N-1,其中N是行数。

lines=['G17 G3 X387.9385 Y200.0000 Z268.4040 R187.9385',
  'G17 G3 X200.0000 Y387.9385 Z268.4040 R187.9385',
  'G17 G3 X200.0000 Y387.9385 Z268.4040 R187.9385',
  'G17 G3 X200.0000 Y353.2089 Z328.5575 R153.2089']

def lines_equal(curr_line, prev_line, compare_char):
   curr_line_parts = curr_line.split(' ')
   prev_line_parts = prev_line.split(' ')

   for item in zip(curr_line_parts, prev_line_parts):
       if item[0].startswith(compare_char):
           return item[0] == item[1]

results = []
prev_line = lines[0]

for line in lines[1:]:
    results.append(lines_equal(line, prev_line, 'Z'))
    prev_line = line

print(results)