0

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?

sugar
  • 3
  • 2

1 Answers1

0

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.

Ignatius Reilly
  • 1,594
  • 2
  • 6
  • 15
  • That's right! Dictionaries can point to nodes coordinates, but I think the same answer can be achieved with the class syntax. – sugar Aug 03 '22 at 06:21
  • Yes, but think in dictionaries as the most basic form of custom object. If you need a dictionary, use a dictionary. If you really need to add more functionality, then go for a class. – Ignatius Reilly Aug 03 '22 at 14:15
  • I understand the structure of the dictionary, it's the key to read the value. In addition, I want to ask if I create an element (composed of four nodes), can I still use the new defined dictionary? Thanks for your valuable advice! – sugar Aug 04 '22 at 03:54
  • If the object you need to create has a complex structure, or many associated methods, a class can help you to organize the logic behind it. My recommendation is to avoid re-discovering the wheel: do not create a class only to store a bunch of key-value associations. Maybe [this](https://stackoverflow.com/questions/4045161/should-i-use-a-class-or-dictionary) and [this](https://stackoverflow.com/a/11108184/15032126) can help. – Ignatius Reilly Aug 04 '22 at 04:44