ankit
ankit

Reputation: 61

How to concatenate output data coming out from for loop/function

I have a data set as a list. From that list I need to find a keyword, and if found, I should be able to extract the complete information of that element.

att =['Email/[email protected]', 'CountryCode/US','CountryCode/UK', 'ID/12345']

from the above list, if I search only CountryCode, then the output should come as:

['CountryCode/US','CountryCode/UK']

Below is my code which I am trying, but it is returning only a single value.

Can some one help me with this code, to return all of the values as :

['CountryCode/US','CountryCode/UK']
def att_func(field,data):
    for i, j in enumerate(data):
        # print(i,j)
        if field in j:
            return [data[i]]


att =['Email/[email protected]', 'CountryCode/US','CountryCode/UK', 'ID/12345']

field ='CountryCode'

Cntry = att_func('CountryCode',att)
print(Cntry)

Upvotes: 0

Views: 63

Answers (3)

Valentin B.
Valentin B.

Reputation: 622

att = ['Email/[email protected]', 'CountryCode/US','CountryCode/UK', 'ID/12345']
out = [item for item in att if "CountryCode" in item]

Done !

Your att_func should look like this:

def att_func(needle, haystack):
    return [item for item in haystack if needle in item]

More on list comprehensions.

Upvotes: 0

Harsha Biyani
Harsha Biyani

Reputation: 7268

Reason : This is because you are returning as soon as single data is getting.

Solution : Collect all data in list and the return collected data.

Try:

def att_func(field,data):
    final_data = []
    for i, j in enumerate(data):
        # print(i,j)
        if field in j:
            final_data.append(data[i])
    return final_data


att =['Email/[email protected]', 'CountryCode/US','CountryCode/UK', 'ID/12345']

field ='CountryCode'

Cntry = att_func('CountryCode',att)
print(Cntry)

Upvotes: 0

Sayse
Sayse

Reputation: 43300

You're returning early in your for loop so you'll never get past the first position where the field exists, you can either use yield instead of return and make your function return a generator or just use a list comprehension

def att_func(field, data):
    return [i for i in data if field in i]

Upvotes: 2

Related Questions