To insert data into a Python list structure

Asked 2 years ago, Updated 2 years ago, 97 views

There are two CSV data, one for coordinate X and Y axis, and the other for which group belongs. The form of the data is as follows.

#coordinate CSV
x,y
126.9604, 37.55781
126.9729, 27.56278
126.9734, 37.56292
126.9797, 37.56395
126.8711, 37.56713
126.9934, 37.55459
126.9934, 37.55459
126.6453, 37.45654
126.9875, 37.45642
#Group number coordinate CSV
1
1
1
2
2
2
2
3
3

Through this data, I want to make coordinates with the same group number included in the same list. For example, below

[{126.9604, 37.55781}, {126.9729, 27.56278}, {126.9734, 37.56292}] #Group 1
[{126.9797, 37.56395}, {126.8711, 37.56713}, {126.9934, 37.55459}, {126.9934, 37.55459}] #2 group
[{126.6453, 37.45654}, {126.9875, 37.45642}] #3 group

How can I fill it out to reflect the group number? I beg you.

python list

2022-09-22 19:43

1 Answers

I think it would be nice to use hash (dictionary in python).

I think you already know how to read csv, so I won't explain it separately. The group number should be set as a key, and the value of the key should be set as a list that stores coordinate values.

coordinates = [
    [126.9604, 37.55781],
    [126.9729, 27.56278],
    [126.9734, 37.56292],
    [126.9797, 37.56395],
    [126.8711, 37.56713],
    [126.9934, 37.55459],
    [126.9934, 37.55459],
    [126.6453, 37.45654],
    [126.9875, 37.45642]
]
group_numbers= [
    1,
    1,
    1,
    2,
    2,
    2,
    2,
    3,
    3
]

answer = {}

for group_number, coord in zip(group_numbers, coordinates):
    try:
        answer[group_number].append(coord)
    except KeyError:
        answer[group_number] = [coord]

print(answer)


2022-09-22 19:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.