Home > Enterprise >  Finding if a string exist in list within a list
Finding if a string exist in list within a list

Time:09-22

I am trying to find if a string Date is present in a list of items. If Date is not present i want to get a null list.

Code

  data = [['Organizations', 'Name', 'San Franciso', 11, 32],
     ['CreativeTeamRoles', 'Description', 'Music Director', 945, 959],
     ['Persons', 'FullName', 'Salonen', 5761, 5778],
     ['CreativeTeamRoles', 'Description', 'Conductor', 7322, 7331],
     ['SoloistRoles', 'Description', 'Piano', 7627, 7632],
     ['Performances', 'Starttime', '2:00PM', 8062, 8068],
     ['Performances', 'Date', '2021-05-07', 8247, 8252],
     ['Performances', 'Endtime', '7:30PM', 8262, 8268]]
output_list = [item for items in data for item in items if 'Date' in item]

Since it has both strings and integers i am getting an error

TypeError: argument of type 'int' is not iterable

CodePudding user response:

try this:

[d for d in data if 'Date' in d]

CodePudding user response:

As from the question,

It seems like you want the Boolean value of the presence of a given string inside a nested list, you can try like this, which returns only True and False

print(any([True for i in data if 'Data' in i else False]))

If you want the list that contains the given string, then -

print([*i for i in data if 'Data' in i])

tell me if this is okay for you...

  • Related