0

I have (result from a query) my_list = [('a',),('b',),('c',),('g',),('j',)]
I want to translate it to ['a','b','c']
What I have so far r = [rs for rs in my_list if rs not in[('g',),('j',)]]

This will fetch ('a',),('b',),('c',)

Itay Moav -Malimovka
  • 52,579
  • 61
  • 190
  • 278

3 Answers3

1
inputs = [('a',),('b',),('c',),('g',),('j',)]

r = [left for (left,) in inputs if left not in ['g','j']]

Be careful that list is an important function in python, using it as a variable name will override it.

Bouke Versteegh
  • 4,097
  • 1
  • 39
  • 35
0

You need to select the first element of the tuple:

r = [rs[0] for rs in list if rs not in[('g',),('j',)]]
#       ^
MattDMo
  • 100,794
  • 21
  • 241
  • 231
0

I do not get what the rules are for selecting items, but you want to flatten your initial list (list renamed to l):

[item for sublist in l[:3] for item in sublist]

This returns ['a', 'b', 'c'].

In case you already know the structure of your input list, you do not need to filter each item. In case the filter rules are more complex that your current question suggests, you should specify them.

Community
  • 1
  • 1
Dr. Jan-Philip Gehrcke
  • 33,287
  • 14
  • 85
  • 130