I try to iterate over each line in a list of lists, add an item from each line to a new list, and then find unique items in the new list.
I understand that I can do this easily with a for loop. I try a different route because I want to learn more about classes and functions.
Here is an example of a list of lists. The first line is the title:
legislators = [
['last_name', 'first_name', 'birthday', 'gender', 'type', 'state', 'party'],
['Bassett', 'Richard', '1745-04-02', 'M', 'sen', 'DE', 'Anti-Administration'],
['Bland', 'Theodorick', '1742-03-21', '', 'rep', 'VA', ''],
['Burke', 'Aedanus', '1743-06-16', '', 'rep', 'SC', ''],
['Carroll', 'Daniel', '1730-07-22', 'M', 'rep', 'MD', ''],
['Clymer', 'George', '1739-03-16', 'M', 'rep', 'PA', ''],
['Contee', 'Benjamin', '', 'M', 'rep', 'MD', ''],...]
Here is my code:
import csv
f = open("legislators.csv")
csvreader = csv.reader(f)
legislators = list(csvreader)
class Dataset:
def __init__(self, data):
self.header = data[0]
self.data = data[1:]
legislators_dataset = Dataset(legislators)
def the_set_maker(dataset):
gender = []
for each in dataset:
gender.append(each[3])
return set(gender)
t=the_set_maker(legislators_dataset)
print(t)
I get the following error:
TypeErrorTraceback (most recent call last)
<ipython-input-1-d65cb459931b> in <module>()
20 return set(gender)
21
---> 22 t=the_set_maker(legislators_dataset)
23 print(t)
<ipython-input-1-d65cb459931b> in the_set_maker(dataset)
16 def the_set_maker(dataset):
17 gender = []
---> 18 for each in dataset:
19 gender.append(each[3])
20 return set(gender)
TypeError: 'Dataset' object is not iterable
I think the answer is trying to create a method using def __iter__(self)in my class Dataset, but I could not get it to work. Is this the right way? If not, which is better?