+ 2
How can I get the no of items in a loop in python
I have a csv file containing items. So I want to determine the no of items in the 2nd row of the csv file. I want to use the no of items to calculate average of the items
11 odpowiedzi
+ 2
Need more info on that "items". A copy of a line from the CSV file might help to improve clarity.
+ 2
If you already have a loop, can you simply create a variable that gets incremented during each loop?
i++
+ 2
The issues is that some of the items in the csv column are duplicates. Hence,
counter = 0
for I in resources:
counter += 1
Print(counter)
Did not give the correct values
+ 2
If possible, you could use pandas data frames and you can analyse your data in quite a variety of ways.
Otherwise you could store the data in a set and a list separately.
Len(set(values_list))
would give you the number of unique elements in that row.
Len(values_list)
would return the number total. Subtract one from the other and you have number of duplicates.
+ 1
Whenever I run the iteration, I print the items in the loop but to determine the total no of the items is my issue
+ 1
Can we see just 1 line of that file for an example? pick one that has duplicates. I still am not getting any idea how the data looked like.
+ 1
Take instance:
23467
23467
12345
12345
67890
67890
That is how the items are arranged in the csv column. Hence, I couldn't get the total count using the code above. Is there any way around it? Kindly assist. Thanks
+ 1
G'day Adewale Isaac what about checking for a duplicate and skip that import?
if (*resources(i-1) in var_new_input){
continue;
}
else{
resources(i)=var_new_input;
counter+=1;
}
You may need a much better way of checking for duplicates. Or perhaps importing all the records first, then running your duplicate check and decrementing your counter when the duplicate is removed.
PS: I'm not yet %100 on C pointers...... It may be wrong syntax. Whoops, should be python not C, sorry.
+ 1
HungryTradie Thanks but I need the count of those duplicates as well. I won't want to remove it as it is part of the total. And also can we apply pointers to python code as you solved above. Thanks
+ 1
Velme Your answer solved it. I actually didn't need to use panda but made use of the pseudo code below:
#creating an empty list to accommodate the no of items
new_list =[]
for item in items:
new_list.append(item)
num_of_items_in_list = len(new_list)
print (num_of_items_in_list)
0
Velme Thanks