I have Python nested list that I’m trying to organize and eventually count number of occurrences. The nested list looks like:
[['22', '1'], ['21', '15'], ['11', '3'], ['31', '4'], ['41', '13'],...]
The first I want to do is create a sublist that only contains ‘1’ corresponding to the second item in the nested list. I was able to do this by the following command:
Subbasin_1 = []
Subbasin_1.append([x for x in Subbasins_Imp if x[1] == '1'])
print Subbasin_1
Giving these results, which are correct:
[['21', '1'], ['21', '1'], ['21', '1'], ['21', '1'], ['22', '1'],...]
Now I want to create another sublist that will give me all the ’21’ in the each nested list for Subbasin_1. When I use the same line of script, but change the appropriate items, I get an empty list. Not sure what is going on…?
OS_Count1 = []
OS_Count1.append([x for x in Subbasin_1 if x[0] == '21'])
print OS_Count1
Result is [[]] ??? What’s the difference between the two?
Thanks for any help…
I don’t believe that your
line could be produced by the code you gave. Your
Subbasin_1.appendline appends a list to the empty list Subbasin_1, so you should get something likewith one extra level of nesting.
If you avoid the unnecessary construction of an empty list + append, you should get what you want:
Alternatively, you could simply replace append by extend. I don’t recommend this, but it might help you to see what’s happening: