How to list int in the for loop

Question:

I am currently encountering some difficulties, please explain to me first, thank you!

I have created some data in the G2.txt file, the internal node has 16 lines, and I want to arrange these numbers in an orderly manner.

file=open('G2.txt','r')
for line in file.readlines():
    transform_str=line.split(',')
    number_node=int(transform_str[0])
    x=int(transform_str[1])
    y=int(transform_str[2])
    lst=[number_node]
    print(lst)

output:

[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]
[10]
[11]
[12]
[13]
[14]
[15]
[16]

but I want the output as:

[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]

what should I do?

Asked By: sugar

||

Answers:

You need to initialize a list before the for loop and append items to it. Once you’re done, you could print the entire list with print.

file=open('G2.txt','r')

result = []

for line in file.readlines():
    transform_str=line.split(',')
    number_node=int(transform_str[0])
    x=int(transform_str[1])
    y=int(transform_str[2])
    result.append(number_node)

print(result)
Answered By: Preet Mishra

You can use append() to generate a list during the loop. However, note that in each iteration you’re re-assigning values to x and y. So, whatever is stored in one iteration is lost in the next one.

These seem to be coordinates associated to the nodes, so you probably want to store them in some structure that can hold the association node -> (x,y). And that’s what dictionaries are for.

nodes = {}

with open('G2.txt','r') as file:
    for line in file.readlines():
        transform_str = line.split(',')
        nodes[int(transform_str[0])] = (int(transform_str[1]), int(transform_str[2]))

Now you can print the nodes (keys) with print(list(nodes.keys())), and you can access the x, y coordinates of any node with nodes[number].

Note that it’s a good practice to open files using with or try - except to ensure the file is closed even if there’s an error.

Answered By: Ignatius Reilly
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.