0

I have a list like below - from this i have filter the tables that begin with 'test:SF.AcuraUsage_' (string matching)

test:SF.AcuraUsage_20150311
test:SF.AcuraUsage_20150312
test:SF.AcuraUsage_20150313
test:SF.AcuraUsage_20150314
test:SF.AcuraUsage_20150315
test:SF.AcuraUsage_20150316
test:SF.AcuraUsage_20150317
test:SF.ClientUsage_20150318
test:SF.ClientUsage_20150319
test:SF.ClientUsage_20150320
test:SF.ClientUsage_20150321

I am using this for loop but not sure why it does not work:

for x in list:
 if(x  'test:SF.AcuraUsage_'):
   print x

I tried this out:

for x in list:
  alllist = x

vehiclelist = [x for x in alllist if x.startswith('geotab-bigdata-test:StoreForward.VehicleInfo')]

Still i get the error ' dictionary object has no attribute startswith'.

user3447653
  • 3,968
  • 12
  • 58
  • 100
  • Possible Duplicate of [List comprehension with if statement](http://stackoverflow.com/questions/15474933/list-comprehension-with-if-statement) – Bhargav Rao Jun 14 '16 at 17:08

3 Answers3

3

You shouldn't name your list list, since it overrides the built-in type list

But, if you'd like to filter that list using Python, consider using this list comprehension:

acura = [x for x in list if x.startswith('test:SF.AcuraUsage')]

then, if you'd like to output it

for x in acura:
    print(x)
Brian
  • 1,659
  • 12
  • 17
0

List comprehensions are good for that.

Get a list with all the items that begin with 'test:SF.AcuraUsage_' :

new_list = [x for x in list if x.startswith('test:SF.AcuraUsage_' ')]

Or the items that do not begin with 'test:SF.AcuraUsage_' :

new_list = [x for x in list if not x.startswith('test:SF.AcuraUsage_' )]
C14L
  • 12,153
  • 4
  • 39
  • 52
  • I get the error "Table has no attribute StartsWith'. Sorry guys, i thought this statement returns a list, but it returns a table object. list = bq.DataSet('bigdatatest:SF') This statement returns a list of tables as shown in my question. – user3447653 Jun 13 '16 at 14:31
  • If you want to filter a a very large list (millions of rows) and you are getting it from a iterator, it may be better to use a generator function and yield the resulting data rows. So you don't have to load it all into memory at once and then make a copy of part of it. – C14L Jun 13 '16 at 14:35
  • If those items are objects, the filtering still works in a similar way. Just filter on some attribute. – C14L Jun 13 '16 at 14:37
  • I tried iterating through the table and storing in a list. Then i iterated through the list for the check. Still I get the error ' dictionary object has no attribute startswith'. I have added that code in the question. – user3447653 Jun 13 '16 at 14:39
0

using re module:

import re
for x in list:
  ret = re.match('test:SF.AcuraUsage_(.*)',x)
  if ret:
    print(re.group())
girardengo
  • 726
  • 12
  • 16