简体   繁体   中英

Putting multiple line input in seperate lists, Python

I want to make a code to find the fastest way in a tree, but I'm having trouble with getting the input right. The input exists out of number of nodes, followed by the lines with the neighbouring nodes for each node, and last is a line with the start and finish node.

6
1 4
0 2 4
1 3
2 4 5
0 1 3
3
0 3

This would be 6, nodes and node 0 would be connected with node 1 and 4, node 1 connected with node 0, node 2 and node 4, etc. and we would want to find a path from node 0 to node 3.

So far I have

numberofnodes=int(input())
no_of_lines = numberofnodes
lines = ""
for i in range(numberofnodes):
    lines+=input()+"\n"
startfinish=(input().split())

if I print the number of nodes, lines and startfinish I get

6
1 4
0 2 4
1 3
2 4 5
0 1 3
3

['0', '3']

I've been trying to get the neighbours of the nodes in a list as well, so the rest of my code works, but I'm having trouble with that. Everything I tried put them all on 1 list, but I want them in seperate lists.

First of all, finding fastest (you probably mean shortest) way (path) in a tree is nonsense, because there is only 1 path to each node. You probably want to do that on a graph ( tree is a special type of graph ).

Terminology aside, start with empty list lines = [] , that will hold the other lists. In your for cycle you also need to split the line as you do with the last one, and probably it would be useful to interpret the strings as numbers. U can use append to add item to list, see the documentation .

lines = []
for i in range(numberofnodes):
    line = []
    for word in input().split():
        line.append(int(word))
    lines.append(line)

Printing lines (now a list of lists, ie nested list) outputs following:

[[1, 4], [0, 2, 4], [1, 3], [2, 4, 5], [0, 1, 3], [3]]

Have a look at some basic python tutorials on lists, and work your way up to the harder exercises gradually, do not try to program hard problems until you fully understand how to use lists.

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