Finding a list in a python list

I have a list containing other lists as items.

mylist=[
         [1, 'Asfoor', 'a', 'b', 'c'], 
         [2, 'deek', 'j', 'a', 'k'], 
         [3, 'bata', 'k', 'a', 'p'],
         [4,'farkha','v','m','k']
       ]

      

Now I want to find occurrences in the list of other list items 'a' and 'k' in the list above and need the output to be in a specific format.

second list=['a','k']

      

For example, if any element of the first list contains the 'a' element from the second list, then the output list should look something like this:

['a',
     [
         [1, 'Asfoor', 'a', 'b', 'c'], 
         [2, 'deek', 'j', 'a', 'k'], 
         [3, 'bata', 'k', 'a', 'p']
     ]
]

      

And similarly, if the list contains "k", then output as shown below:

['k',
         [2, 'deek', 'j', 'a', 'k'], 
         [3, 'bata', 'k', 'a', 'p'],
         [4,'farkha','v','m','k']
]

      

Any good python way of doing this would be much appreciated.

+3


source to share


3 answers


You can do something like this:

def found(a, key):
    return key in a:


keys = ['a', 'k']

final = []
for j in keys:
    final.append([j , [k for k in mylist if found(k, j)]])

# Or simply within list comprehension:
# final = [[j , [k for k in mylist if found(k, j)]] for j in keys]


print(final)

      



Output:

[['a',
  [[1, 'Asfoor', 'a', 'b', 'c'],
   [2, 'deek', 'j', 'a', 'k'],
   [3, 'bata', 'k', 'a', 'p']]],
 ['k',
  [[2, 'deek', 'j', 'a', 'k'],
   [3, 'bata', 'k', 'a', 'p'],
   [4, 'farkha', 'v', 'm', 'k']]]]

      

+1


source


You can check if a string is in the list:

for row in my_list:  # finding 'a' in list
    if 'a' in row:
        print(row)

for row in my_list:  # finding 'k' in list
    if 'k' in row:
        print(row)

      



To print a string you will need to use "\ t" (tab) and some other characters based on the desired output format

0


source


print([sublist for sublist in mylist if 'a' in sublist])
# returns:
[
  [1, 'Asfoor', 'a', 'b', 'c'],
  [2, 'deek', 'j', 'a', 'k'],
  [3, 'bata', 'k', 'a', 'p']
]

      

0


source







All Articles