I have a file in *.las format and i wish to count how many points are Return1, Return2,…,Return5
I use a If…Else Statements, but i wish to understand if there is a way more elegant and code saving. Thanks in advance for help and tips.
Return1 = 0
Return2 = 0
Return3 = 0
Return4 = 0
Return5 = 0
count = 0
for p in lasfile.File(inFile,None,'r'):
count +=1
if p.return_number == 1:
Return1 += 1
elif p.return_number == 2:
Return2 += 1
elif p.return_number == 3:
Return3 += 1
elif p.return_number == 4:
Return4 += 1
elif p.return_number == 5:
Return5 += 1
You can use a
dictof counters (in this case it can also be a list).defaultdictis quite convenient:Edit: I’m not sure if DSM is posting a separate answer with
Counterexamples, so I’m going to reply to the OP’s question here:Counterwill count values in the iterable you give it. The iterable is supposed to be homogenic. For example, ifscan_angles can take values of1,2, etc., then you can’t use the sameCounterfor both and get correct results. If the values don’t overlap, you can get correct results, but your code will be confusing and hard to understand. I’d suggest to use twoCounter‘s: one forreturn_numbers and one forscan_angle‘s. You can use the same loop to populate both easily (and the same stands fordefaultdict‘s), but if you want to compress creation and filling of twoCounter‘s into one statement, you’ll need something likeNote that at least on Python 2 it will produce a list, so all data will be held in memory at once at some point.
Yet, the much simpler ways to go are:
use two
defaultdicts:or fill two
Counters in two different reads of the file: