'get such a number of elements as a percentage from a list [closed]
I am trying to write a function that will allow me to extract a subset from a defined list. Note that the function returns two things:
- The original list with the subset removed S = S - S'
- the new list which contains only the subset S'
Example :
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
new_list = get_purcentage(list, purcentage = 0.3)
# list should now be :
# list = [1, 2, 3, 4, 5, 6, 7]
# new_list should now be :
# new_list = [8, 9, 10]
I tried to use a library like train_test_split from sklearn.model_selection and it works as I want it to, but I would like to have my own code
Note: the order doesn't matter, the items can be taken randomly
Solution 1:[1]
self.object.save() keeps overwriting your object. You want to create separate db records from each line of your textarea input.
Better create a simple form forms.Form for data entry instead of ModelForm.
Then on the its form_valid, iterate through the lines and create objects. Each iteration should create a new object and save.
You need to get rid of the textarea field as well.
If its a lot of data, it’s better to use bulk create function for performance.
Solution 2:[2]
I found the solution after reading this https://stackoverflow.com/a/33027228/13152307 .
I should set the primary key to none at the beginning of each iteration.
for each_line in data_line_list:
self.object.pk = None #add this line
each_line_list = each_line.split(",")
self.object.part_number = each_line_list[0]
self.object.length = each_line_list[1]
self.object.weight = each_line_list[2]
self.object.height = each_line_list[3]
self.object.save()
I understand that it may not be a good way to do so, but at least it works now.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Amrit Bera |
| Solution 2 | Young Ker |
