Skip to content
Advertisement

Alternative to “for” LINQ equivalent of Where?

I have a CSV file contents in a variable raw_data. I only need certain rows depending on whether the first element of the row (row_split[0]) matches a price_number. The below code works fine however coming from a C# background I know there is a LINQ equivalent. Is there anything in Python that use Where or Any which also includes the row.split(',').

for row in raw_data:
    row_split = row.split(',')
    if str(row_split[0]) == price_number:
        filtered_data.append(row)

Advertisement

Answer

I think you can do it using list comprehension

filtered_data = [row for row in row_data if str(row.split(',')[0]) == price_number]
Advertisement