Home > Net >  How do you append a row of data to a list
How do you append a row of data to a list

Time:08-24

For example... The following are stored in a dictionary variable called ID_DATA

[0,John,male,$2400]
[1,mary,female,$2700]
[2,janie,female,$6790]
[3,adex,male,$3300]
[4,julie,female,$5400]

I want to loop through the list and append only the rows with only male in another list variable called ID_MALE

Can anyone help out ???.

CodePudding user response:

Are they stored in a dictionary of lists or a list of lists?

If it's the latter and the gender is always in the 2nd spot in each list (the second column) then you could just do something like this:

ID_DATA = [['John','male','$2400'],['mary','female','$2700'],['janie','female','$6790'],['adex','male','$3300'],['julie','female','$5400']]
ID_MALE = []
for row in ID_DATA:
    if row[2] == 'male':
       ID_MALE.append(row)

print(ID_MALE)

Which prints

[['John', 'male', '$2400'], ['adex', 'male', '$3300']]

CodePudding user response:

i think you can use list tuples first for saving data then use lambda and filter

data_Id= [
       [0,'John','male',2400],
       [1,'mary','female',2700],
       [2,'janie','female',6790],
       [3,'adex','male',3300],
       [4,'julie','female',5400]
       ]
    str='male'

   ID_MALE =filter(lambda x:str in x,data_Id)
   print(list(ID_MALE))

Output

[[0, 'John', 'male', 2400], [3, 'adex', 'male', 3300]]
  • Related