Home > database >  How to list int in the for loop
How to list int in the for loop

Time:08-03

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?

CodePudding user response:

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.

CodePudding user response:

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)
  • Related