how can a find a patter of numbers in consecutive lines with python?Finding the index of an item given a list containing it in PythonHow can I safely create a nested directory in Python?How can I remove a trailing newline in Python?How to get the current time in PythonHow can I make a time delay in Python?How do I get the number of elements in a list in Python?How do I concatenate two lists in Python?How to print a number with commas as thousands separators in JavaScriptHow to read a file line-by-line into a list?“Large data” work flows using pandas

Why airport relocation isn't done gradually?

Symmetry in quantum mechanics

Is it legal to have the "// (c) 2019 John Smith" header in all files when there are hundreds of contributors?

Is this food a bread or a loaf?

COUNT(*) or MAX(id) - which is faster?

When blogging recipes, how can I support both readers who want the narrative/journey and ones who want the printer-friendly recipe?

Why do we use polarized capacitors?

"My colleague's body is amazing"

Can a planet have a different gravitational pull depending on its location in orbit around its sun?

What is the offset in a seaplane's hull?

Is ipsum/ipsa/ipse a third person pronoun, or can it serve other functions?

How could a lack of term limits lead to a "dictatorship?"

Why is my log file so massive? 22gb. I am running log backups

New order #4: World

I see my dog run

"listening to me about as much as you're listening to this pole here"

Email Account under attack (really) - anything I can do?

What causes the sudden spool-up sound from an F-16 when enabling afterburner?

Need help identifying/translating a plaque in Tangier, Morocco

Doomsday-clock for my fantasy planet

Is there a name of the flying bionic bird?

Is it wise to focus on putting odd beats on left when playing double bass drums?

Why do UK politicians seemingly ignore opinion polls on Brexit?

Does it makes sense to buy a new cycle to learn riding?



how can a find a patter of numbers in consecutive lines with python?


Finding the index of an item given a list containing it in PythonHow can I safely create a nested directory in Python?How can I remove a trailing newline in Python?How to get the current time in PythonHow can I make a time delay in Python?How do I get the number of elements in a list in Python?How do I concatenate two lists in Python?How to print a number with commas as thousands separators in JavaScriptHow to read a file line-by-line into a list?“Large data” work flows using pandas






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








2















Im learning python but i have some problems with my scripts yet.



I have a file similar to:



1 5
2 5
3 5
4 2
5 1
6 7
7 7
8 8


I want to print the pairs of numbers 2-1 in consecutive lines, just taking the column 2 to find them, and then, print the column 1 and 2 with the results. The result will be similar to this:



4 2 
5 1


I'm trying to do it with python, because my file has 4,000,000 data. So, this is my script:



import linecache

final_lines = []
with open("file.dat") as f:
for i, line in enumerate(f, 1):
if "1" in line:
if "2" in linecache.getline("file.dat", i-1):
linestart = i - 1
final_lines.append(linecache.getline("file.dat", linestart))
print(final_lines)


and the result is:



['2n', '2n', '2n']


What I must to change in my script to fit the result that I want?, Can you guide me please? Thanks a lot.










share|improve this question



















  • 1





    do you need to use linecache? opening a file in python returns an iterator by default

    – aws_apprentice
    Mar 22 at 1:53











  • It's not necessary, but it was an option that I found. So, if it is not necessary, i can remove it.

    – Hdez
    Mar 22 at 1:57

















2















Im learning python but i have some problems with my scripts yet.



I have a file similar to:



1 5
2 5
3 5
4 2
5 1
6 7
7 7
8 8


I want to print the pairs of numbers 2-1 in consecutive lines, just taking the column 2 to find them, and then, print the column 1 and 2 with the results. The result will be similar to this:



4 2 
5 1


I'm trying to do it with python, because my file has 4,000,000 data. So, this is my script:



import linecache

final_lines = []
with open("file.dat") as f:
for i, line in enumerate(f, 1):
if "1" in line:
if "2" in linecache.getline("file.dat", i-1):
linestart = i - 1
final_lines.append(linecache.getline("file.dat", linestart))
print(final_lines)


and the result is:



['2n', '2n', '2n']


What I must to change in my script to fit the result that I want?, Can you guide me please? Thanks a lot.










share|improve this question



















  • 1





    do you need to use linecache? opening a file in python returns an iterator by default

    – aws_apprentice
    Mar 22 at 1:53











  • It's not necessary, but it was an option that I found. So, if it is not necessary, i can remove it.

    – Hdez
    Mar 22 at 1:57













2












2








2








Im learning python but i have some problems with my scripts yet.



I have a file similar to:



1 5
2 5
3 5
4 2
5 1
6 7
7 7
8 8


I want to print the pairs of numbers 2-1 in consecutive lines, just taking the column 2 to find them, and then, print the column 1 and 2 with the results. The result will be similar to this:



4 2 
5 1


I'm trying to do it with python, because my file has 4,000,000 data. So, this is my script:



import linecache

final_lines = []
with open("file.dat") as f:
for i, line in enumerate(f, 1):
if "1" in line:
if "2" in linecache.getline("file.dat", i-1):
linestart = i - 1
final_lines.append(linecache.getline("file.dat", linestart))
print(final_lines)


and the result is:



['2n', '2n', '2n']


What I must to change in my script to fit the result that I want?, Can you guide me please? Thanks a lot.










share|improve this question
















Im learning python but i have some problems with my scripts yet.



I have a file similar to:



1 5
2 5
3 5
4 2
5 1
6 7
7 7
8 8


I want to print the pairs of numbers 2-1 in consecutive lines, just taking the column 2 to find them, and then, print the column 1 and 2 with the results. The result will be similar to this:



4 2 
5 1


I'm trying to do it with python, because my file has 4,000,000 data. So, this is my script:



import linecache

final_lines = []
with open("file.dat") as f:
for i, line in enumerate(f, 1):
if "1" in line:
if "2" in linecache.getline("file.dat", i-1):
linestart = i - 1
final_lines.append(linecache.getline("file.dat", linestart))
print(final_lines)


and the result is:



['2n', '2n', '2n']


What I must to change in my script to fit the result that I want?, Can you guide me please? Thanks a lot.







python numbers line-by-line specification-pattern






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 22 at 7:55









U9-Forward

18k51744




18k51744










asked Mar 22 at 1:46









HdezHdez

385




385







  • 1





    do you need to use linecache? opening a file in python returns an iterator by default

    – aws_apprentice
    Mar 22 at 1:53











  • It's not necessary, but it was an option that I found. So, if it is not necessary, i can remove it.

    – Hdez
    Mar 22 at 1:57












  • 1





    do you need to use linecache? opening a file in python returns an iterator by default

    – aws_apprentice
    Mar 22 at 1:53











  • It's not necessary, but it was an option that I found. So, if it is not necessary, i can remove it.

    – Hdez
    Mar 22 at 1:57







1




1





do you need to use linecache? opening a file in python returns an iterator by default

– aws_apprentice
Mar 22 at 1:53





do you need to use linecache? opening a file in python returns an iterator by default

– aws_apprentice
Mar 22 at 1:53













It's not necessary, but it was an option that I found. So, if it is not necessary, i can remove it.

– Hdez
Mar 22 at 1:57





It's not necessary, but it was an option that I found. So, if it is not necessary, i can remove it.

– Hdez
Mar 22 at 1:57












3 Answers
3






active

oldest

votes


















0














would work i think



import re
with open("info.dat") as f:
for match in re.findall("d+ 2[sn]*d+ 1",f.read()):
print match


see also : https://repl.it/repls/TatteredViciousResources



another alternative is



lines = f.readlines()
for line,nextline in zip(lines,lines[1:]):
if line.strip().endswith("2") and nextline.strip().endswith("1"):
print(line+nextline)





share|improve this answer

























  • The last code won't work if '1' is in the last line of the file.

    – U9-Forward
    Mar 22 at 2:03











  • Thanks a lot. it's that I looking for. Cheers.

    – Hdez
    Mar 22 at 2:06


















1














Use a for loop with enumerate with a if statement to condition the lines, and then if the condition is true, append the two lines into the list final_lines:



final_lines = []
with open('file.dat') as f:
lines = f.readlines()
for i,line in enumerate(lines):
if line.split()[1] == '2' and lines[i+1].split()[1] == '1':
final_lines.extend([line,lines[i+1]])


And now:



print(final_lines)


Would return your desired list.






share|improve this answer






























    0














    You are a beginner at Python which is great, so I am going to take a more elementary approach. It's a huge file so you are better reading a line at at time and keeping only that line, but you actually need two lines to identify the pattern so keep two. consider the following:



     fp = open('file.dat')
    last_line = fp.readline()
    next_line = fp.readline()
    while next_line:
    # logic to split the lines into a pair
    # of numbers and check to see if the
    # 2 and 1 end last_line and next_line
    # and outputting
    last_line = next_line
    next_line = fp.readline()


    This follows good, readable software patterns, and requires a minimum of resources.






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55291730%2fhow-can-a-find-a-patter-of-numbers-in-consecutive-lines-with-python%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      would work i think



      import re
      with open("info.dat") as f:
      for match in re.findall("d+ 2[sn]*d+ 1",f.read()):
      print match


      see also : https://repl.it/repls/TatteredViciousResources



      another alternative is



      lines = f.readlines()
      for line,nextline in zip(lines,lines[1:]):
      if line.strip().endswith("2") and nextline.strip().endswith("1"):
      print(line+nextline)





      share|improve this answer

























      • The last code won't work if '1' is in the last line of the file.

        – U9-Forward
        Mar 22 at 2:03











      • Thanks a lot. it's that I looking for. Cheers.

        – Hdez
        Mar 22 at 2:06















      0














      would work i think



      import re
      with open("info.dat") as f:
      for match in re.findall("d+ 2[sn]*d+ 1",f.read()):
      print match


      see also : https://repl.it/repls/TatteredViciousResources



      another alternative is



      lines = f.readlines()
      for line,nextline in zip(lines,lines[1:]):
      if line.strip().endswith("2") and nextline.strip().endswith("1"):
      print(line+nextline)





      share|improve this answer

























      • The last code won't work if '1' is in the last line of the file.

        – U9-Forward
        Mar 22 at 2:03











      • Thanks a lot. it's that I looking for. Cheers.

        – Hdez
        Mar 22 at 2:06













      0












      0








      0







      would work i think



      import re
      with open("info.dat") as f:
      for match in re.findall("d+ 2[sn]*d+ 1",f.read()):
      print match


      see also : https://repl.it/repls/TatteredViciousResources



      another alternative is



      lines = f.readlines()
      for line,nextline in zip(lines,lines[1:]):
      if line.strip().endswith("2") and nextline.strip().endswith("1"):
      print(line+nextline)





      share|improve this answer















      would work i think



      import re
      with open("info.dat") as f:
      for match in re.findall("d+ 2[sn]*d+ 1",f.read()):
      print match


      see also : https://repl.it/repls/TatteredViciousResources



      another alternative is



      lines = f.readlines()
      for line,nextline in zip(lines,lines[1:]):
      if line.strip().endswith("2") and nextline.strip().endswith("1"):
      print(line+nextline)






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Mar 22 at 2:30

























      answered Mar 22 at 1:59









      Joran BeasleyJoran Beasley

      74.2k683122




      74.2k683122












      • The last code won't work if '1' is in the last line of the file.

        – U9-Forward
        Mar 22 at 2:03











      • Thanks a lot. it's that I looking for. Cheers.

        – Hdez
        Mar 22 at 2:06

















      • The last code won't work if '1' is in the last line of the file.

        – U9-Forward
        Mar 22 at 2:03











      • Thanks a lot. it's that I looking for. Cheers.

        – Hdez
        Mar 22 at 2:06
















      The last code won't work if '1' is in the last line of the file.

      – U9-Forward
      Mar 22 at 2:03





      The last code won't work if '1' is in the last line of the file.

      – U9-Forward
      Mar 22 at 2:03













      Thanks a lot. it's that I looking for. Cheers.

      – Hdez
      Mar 22 at 2:06





      Thanks a lot. it's that I looking for. Cheers.

      – Hdez
      Mar 22 at 2:06













      1














      Use a for loop with enumerate with a if statement to condition the lines, and then if the condition is true, append the two lines into the list final_lines:



      final_lines = []
      with open('file.dat') as f:
      lines = f.readlines()
      for i,line in enumerate(lines):
      if line.split()[1] == '2' and lines[i+1].split()[1] == '1':
      final_lines.extend([line,lines[i+1]])


      And now:



      print(final_lines)


      Would return your desired list.






      share|improve this answer



























        1














        Use a for loop with enumerate with a if statement to condition the lines, and then if the condition is true, append the two lines into the list final_lines:



        final_lines = []
        with open('file.dat') as f:
        lines = f.readlines()
        for i,line in enumerate(lines):
        if line.split()[1] == '2' and lines[i+1].split()[1] == '1':
        final_lines.extend([line,lines[i+1]])


        And now:



        print(final_lines)


        Would return your desired list.






        share|improve this answer

























          1












          1








          1







          Use a for loop with enumerate with a if statement to condition the lines, and then if the condition is true, append the two lines into the list final_lines:



          final_lines = []
          with open('file.dat') as f:
          lines = f.readlines()
          for i,line in enumerate(lines):
          if line.split()[1] == '2' and lines[i+1].split()[1] == '1':
          final_lines.extend([line,lines[i+1]])


          And now:



          print(final_lines)


          Would return your desired list.






          share|improve this answer













          Use a for loop with enumerate with a if statement to condition the lines, and then if the condition is true, append the two lines into the list final_lines:



          final_lines = []
          with open('file.dat') as f:
          lines = f.readlines()
          for i,line in enumerate(lines):
          if line.split()[1] == '2' and lines[i+1].split()[1] == '1':
          final_lines.extend([line,lines[i+1]])


          And now:



          print(final_lines)


          Would return your desired list.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 22 at 1:58









          U9-ForwardU9-Forward

          18k51744




          18k51744





















              0














              You are a beginner at Python which is great, so I am going to take a more elementary approach. It's a huge file so you are better reading a line at at time and keeping only that line, but you actually need two lines to identify the pattern so keep two. consider the following:



               fp = open('file.dat')
              last_line = fp.readline()
              next_line = fp.readline()
              while next_line:
              # logic to split the lines into a pair
              # of numbers and check to see if the
              # 2 and 1 end last_line and next_line
              # and outputting
              last_line = next_line
              next_line = fp.readline()


              This follows good, readable software patterns, and requires a minimum of resources.






              share|improve this answer



























                0














                You are a beginner at Python which is great, so I am going to take a more elementary approach. It's a huge file so you are better reading a line at at time and keeping only that line, but you actually need two lines to identify the pattern so keep two. consider the following:



                 fp = open('file.dat')
                last_line = fp.readline()
                next_line = fp.readline()
                while next_line:
                # logic to split the lines into a pair
                # of numbers and check to see if the
                # 2 and 1 end last_line and next_line
                # and outputting
                last_line = next_line
                next_line = fp.readline()


                This follows good, readable software patterns, and requires a minimum of resources.






                share|improve this answer

























                  0












                  0








                  0







                  You are a beginner at Python which is great, so I am going to take a more elementary approach. It's a huge file so you are better reading a line at at time and keeping only that line, but you actually need two lines to identify the pattern so keep two. consider the following:



                   fp = open('file.dat')
                  last_line = fp.readline()
                  next_line = fp.readline()
                  while next_line:
                  # logic to split the lines into a pair
                  # of numbers and check to see if the
                  # 2 and 1 end last_line and next_line
                  # and outputting
                  last_line = next_line
                  next_line = fp.readline()


                  This follows good, readable software patterns, and requires a minimum of resources.






                  share|improve this answer













                  You are a beginner at Python which is great, so I am going to take a more elementary approach. It's a huge file so you are better reading a line at at time and keeping only that line, but you actually need two lines to identify the pattern so keep two. consider the following:



                   fp = open('file.dat')
                  last_line = fp.readline()
                  next_line = fp.readline()
                  while next_line:
                  # logic to split the lines into a pair
                  # of numbers and check to see if the
                  # 2 and 1 end last_line and next_line
                  # and outputting
                  last_line = next_line
                  next_line = fp.readline()


                  This follows good, readable software patterns, and requires a minimum of resources.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 24 at 5:41









                  John M I DavisJohn M I Davis

                  914




                  914



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55291730%2fhow-can-a-find-a-patter-of-numbers-in-consecutive-lines-with-python%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                      Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                      Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript