简体   繁体   English

在python中同时读取两个列表中的输入

[英]Reading input in two lists simultaneously in python

I was solving a problem on hackerrank and encountered a problem reading inputs. 我正在解决有关hackerrank的问题,并且在读取输入内容时遇到了问题。

The input format is: 输入格式为:

First line: A number n , which tells the no. 第一行:一个数字n ,它表示否。 of lines I have to read. 行我必须阅读。

n lines: Two space separated values, eg: n行:两个空格分隔的值,例如:

1 5 1 5

10 3 10 3

3 4 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]. 因此,列表“ a”应为[1,10,3],列表“ b”应为[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(' ')) ltr [i],dist [i] = map(int,raw_input()。split(''))

IndexError: list assignment index out of range. IndexError:列表分配索引超出范围。

This is a common error with Python beginners. 这是Python初学者的常见错误。

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. 您试图将输入的值分配给列表distltr特定单元格,但是由于它们是空列表,所以没有可用的单元格。 The index i is out of range because there is yet no range at all for the index. 索引i超出范围,因为该索引根本没有范围。

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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