list comprehension with input().split()

Viewed 676

I have to read N then N tuples of two numbers as shown in the example below:

3
1 85
2 91
3 73

After that I want to sort them based on the second element, with ties broken by the order they came into input. To do that I wanted to save a tuple with 3 elements but I can't figure out how to put that into a list comprehension syntax.

I want a comprehension that would be equivalent to:

n = int(input())
l = []
for i in range(n):
    v1, v2 = input().split()
    l.append((int(v1), int(v2), i))

Here is what I've tried:

n = int(input())
l = [(int(v1), int(v2), i) for v1, v2 in input().split() for i in range(n)]
3 Answers

Use tuple() and list comprehension:

num_tuples = int(input())
lst = [tuple([int(x) for x in input().split()] + [i]) for i in range(num_tuples)]
print(lst)

Example input:

2
1 2
3 4

Output:

[(1, 2, 0), (3, 4, 1)]

You could do something like this:

l = [(*map(int, input().split()), i) for i in range(int(input()))]

But this is pretty confusing and unreadable, why do something like this when your for-loop is perfectly adequate?

Let's start by writing the program out without condensing the syntax to establish our starting point

n = int(input())
l = []
for i in range(n):
    v1, v2 = input().split()
    l.append((int(v1), int(v2), i))

l = sorted(l, key=lambda x: (x[1], x[2])) # here is the line I'm adding to sort
print(l)
$ python3 test.py
3
1 85
2 91
7 91
[(1, 85, 0), (2, 91, 1), (7, 91, 2)]

It's a bit complex -- and perhaps worse: very difficult to maintain or read -- to place the two statements in the for loop into a list comprehension (though both of the previous answers show how it can be done), so what I'd suggest here if you want to do a one-liner is to place it in a map with a lambda function, such as:

def my_function(num):
    v1, v2 = input().split()
    return (int(v1), int(v2), num)

n = int(input())
l = map(my_function, range(n))

Nice and readable. And if you also want to do the sort (and everything else) in one line, you can of course do:

sorted(map(my_function, range(int(input())), key=lambda x: (x[1], x[2]))
# 1 2
# 2 3
# [(1, 2, 0), (2, 3, 1)]

Here's what it looks like all together (I'll add a share link once I can figure it out):

enter image description here

Related