简体   繁体   中英

Reading input in two lists simultaneously in python

I was solving a problem on hackerrank and encountered a problem reading inputs.

The input format is:

First line: A number n , which tells the no. of lines I have to read.

n lines: Two space separated values, eg:

1 5

10 3

3 4

I want to read the space separated values in two lists. So list 'a' should be [1,10,3] and list 'b' should be [5,3,4].

Here is my code:

dist = []
ltr = []
n = input()
for i in range(n):
    ltr[i], dist[i] = map(int, raw_input().split(' '))

It gives me following error:

ltr[i], dist[i] = map(int, raw_input().split(' '))

IndexError: list assignment index out of range.

This is a common error with Python beginners.

You are trying to assign the inputted values to particular cells in lists dist and ltr but there are no cells available since they are empty lists. The index i is out of range because there is yet no range at all for the index.

So instead of assigning into the lists, append onto them, with something like

dist = []
ltr = []
n = input()
for i in range(n):
    a, b = map(int, raw_input().split(' '))
    ltr.append(a)
    dist.append(b)

Note that I have also improved the formatting of your code by inserting spaces. It is good for you to follow good style at the beginning of your learning so you have less to overcome later.

This might help you in some way; here's a simpler way to approach this problem as you know " Simple is better than complex. ":

dist=[]
ltr=[]
n=int(raw_input())
for i in range(n):
    dist.append(int(raw_input()))
    ltr.append(int(raw_input()))

print(dist)
print(ltr)

output:

[1, 10, 3]
[5, 3, 4]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM