sports
sports

Reputation: 21

How to search for a string in a list of lists?

I have a list of lists like the below:

pb_file = [ 
    ['n012345_y','n012345_e','n023561234_u','n012345_p','n012345_k']
    ['n124536_i','n1542453_m','n10978_k','n124536_m'] 
]

The search string is

search_string = 'n012345_' 
    

and I want to search for items in pb_file that contain the string 'n012345_'(search_string). How can I get all items that contain 'n012345_' ?

The output should be like this…

output_list = ['n012345_y','n012345_e','n012345_p','n012345_k']

Here is my code:

pb_file = [ ['n012345_y','n012345_e','n023561234_u','n012345_p','n012345_k'], 
              ['n124536_i','n1542453_m','n10978_k','n124536_m'] ]

search_string = 'n012345_' 
output_list = search_string in [j for i in pb_file for j in i]

print (output_list)

But, it displays True or False. I want a list.

Upvotes: 1

Views: 1222

Answers (4)

Alfred Ayi-bonte
Alfred Ayi-bonte

Reputation: 775

import functools
search_string = 'n012345_'
pb_file = [ ['n012345_y','n012345_e','n023561234_u','n012345_p','n012345_k'], 
              ['n124536_i','n1542453_m','n10978_k','n124536_m'] ]
def callback(acc, arr):
  for item in arr:
    if search_string in item:
      acc.append(item)
  return acc

functools.reduce(callback, pb_file, [])

Upvotes: 1

bigbounty
bigbounty

Reputation: 17408

pb_file = [ ['n012345_y','n012345_e','n023561234_u','n012345_p','n012345_k'],['n124536_i','n1542453_m','n10978_k','n124536_m'] ]

output = [entry for main_list in pb_file for entry in main_list if "n012345_" in entry]

Output:

['n012345_y', 'n012345_e', 'n012345_p', 'n012345_k']

Loop through the list and check for substring or equality in the if condition

Upvotes: 0

akazuko
akazuko

Reputation: 1394

You can make use of the following:

output_list = [entry for data in pb_file for entry in data if entry.startswith(search_string)]

Upvotes: 0

Samwise
Samwise

Reputation: 71562

output_list = [item for items in pb_file for item in items if search_string in item]

To break down how this works:

output_list = [
    item                                     # the thing that will be in the output list
    for items in pb_file for item in items   # nested loop for item in each sublist
    if search_string in item                 # item only included if this is true
]

Upvotes: 2

Related Questions