-1

I am a given an input file with values of data to read from, the data is given in a pair of numbers like: (1, 2), (3, 4), (3, 5), (4,9) ..etc.

I must read each of these lines and make each line into a tuple and store the tuples in a list.

So far my code to do this is

def main():
tuples_list = []
    for item in sys.stdin:
        item = tuple(item)
        tuples_list = tuples_list.append(item)

However I have to ignore the first number in the input file and I am confused on how to modify my code to only start storing the values after that

2
  • 3
    The question "Will this work?" can be solved by running the code. Commented Feb 6, 2021 at 16:32
  • Your "pair" of numbers is six numbers? Commented Feb 6, 2021 at 16:37

2 Answers 2

0

No, this wont work. You shouldnt do a = a.append(b), just a.append(b). This works:

# file '1.py'
import sys

def main():
    tuples_list = []
    for item in sys.stdin:
        item = tuple(item)
        tuples_list.append(item)
    print(tuples_list)
main()
#file 'inp.txt'
1 2 3 4 
1 2 4 3
3 3 3 3
$ python 1.py <inp 
[('1', ' ', '2', ' ', '3', ' ', '4', ' ', '\n'), ('1', ' ', '2', ' ', '4', ' ', '3', '\n'), ('3', ' ', '3', ' ', '3', ' ', '3', '\n')]

But, in my opinion, using self-written procedures for file input is a bad idea. As you can see, this code reads characters, not numbers, so you need to fix it manualy, which leads to more code, with bugs, of course, debugging, waste of time, etc. You may want to do instead something like this:

# file inp.txt
1,2
3,4
5,6
import numpy as np
data = np.genfromtxt("inp.txt", delimiter=",")
print(data)

This will give you:

array([[1., 2.],
       [3., 4.],
       [5., 6.]])

This code is way faster than anything you will write(no, see comments below), because it uses numpy functions written in C/Fortran, way simpler to read, it handles any number of digits in line, and need no debugging. Using libraries are often better solution then writing code by yourself.

6
  • Please show your benchmark demonstrating that "This code is way faster ...", because in my benchmark, it's about four times slower. Commented Feb 6, 2021 at 16:57
  • Hmm, strange. I have the following results on my machine. The difference is very large, as you see, so I even stoped pure python version in 1m23s, and numpy is way faster then pure python. But in your benchmark code without numpy is faster. May it be because you use map and line.split() which are optimized and written in C, too? Commented Feb 6, 2021 at 17:18
  • How does your 1.py look like? Commented Feb 6, 2021 at 17:20
  • Ah, I see. Probably what you have in your answer. Which reads from sys.stdin. And you're not entering anything, so of course the code doesn't do anything. You waited for 1m23s for the code to finish while the code was waiting for you to give it some data. Commented Feb 6, 2021 at 17:24
  • oh, my bad. Just checked it - yes, i forgot to add < inp. And with correct input this code really runs slower, you were right. Commented Feb 6, 2021 at 17:28
0

Assuming your input file looks something like this: enter image description here

import sys

def main():
    num = sys.stdin.readline()

    # Removing parantheses
    num = num.replace('(', '').replace(')', '')

    # creating list from input
    ls = [int(x) for x in num.split(',')]

    # Sublisting current list to form list of tuples
    sub = []
    tuples_ls = []

    for i in ls:
        sub += [i]
        
        if len(sub) == 2:
            tuples_ls.append(tuple(sub))
            sub = []

    return tuples_ls
5
  • Would this code do the same? def main(): num = int(sys.stdin.readline()) for line in num: num = line.rstrip() ls = [int(line) for line in num.split(', ')] tuple_ls = tuple(ls) print(tuple_ls)
    – zena g
    Commented Feb 6, 2021 at 21:04
  • @zenag, you cannot define input type as an int and put ',' or ' '. First take it as str then process it to int with correct formatting. Commented Feb 6, 2021 at 21:10
  • How do i process it into an int? I dont understand? wasn't that this line "ls = [int(i) for i in str.split(', ')] return tuple(ls) "
    – zena g
    Commented Feb 6, 2021 at 22:42
  • @zenag I edited answer, check if this is what you are looking for. Commented Feb 7, 2021 at 9:19
  • Hello I figured it out thanks for your help!
    – zena g
    Commented Feb 8, 2021 at 0:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.