I want to make Python repeat simple

Asked 2 years ago, Updated 2 years ago, 16 views

I use multiple repetitive sentences separately, but it's a duplicate content... I want to know how to specify multiple of these at once. The repeat statement I use is

    for n in df2.Mag:
        if n >= 0.1 and n < 0.2
        Mag01 += 1

    for n in df2.Mag:
        if n >= 0.2 and n < 0.3
        Mag02 += 1

    for n in df2.Mag:
        if n >= 0.3 and n < 0.4
        Mag03 += 1

...(omitted)

    for n in df2.Mag:
        if n >= 7.9 and n < 8.0
        Mag89 += 1

I made about 80 of them and used them, but I think I can do it without using it 80 times, so I'm opening them to masters For your information, df2 is a csv file, and I want to check how many values of Mag01 to Mag89 are in the df2 file to make a graph later.

python

2022-09-22 10:37

1 Answers

Why "about 80"? If you don't have the exact number (e.g., something is not continuous), it might be best to write it down one by one and specify it. -_-;

If everything is continuous and accurate, it can be solved within the for statement by dynamically creating a range (0.6, 0.7...) to compare with the Mag** variable.

Turning the following code to JS

var total = 60;
var mags = [];
for (i=0; i < total; i++) {
  var j = i+6;
  var no = ('0' + j).slice(-2);
  mags["Mag"+no] = (i > i*0.6);
}
console.log(mags);

A total of 60 key-value arrays can be photographed on the console. Please refer to it.

[
  Mag06: false,
  Mag07: true,
  Mag08: true,
  ...
]


2022-09-22 10:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.