appending a line to a list based off of a string found in a previous list

Terry Reedy tjreedy at udel.edu
Sat Dec 12 17:17:59 EST 2015


On 12/12/2015 4:48 PM, Pedro Vincenty wrote:
> Hello, I'm wondering how to append a line from a file onto a list(easy part) provided that the line contains strings specific to a previous list I've already made(hard part).  I have this right now,
> for line in satellite_dataread:
>          if any(i in line for i in list2):
>              line= line.strip()
>              satellite, country= line.split(',')
>              satellite_origin_list.append(country)
>
> the statement if statement seems to work as I take it out of the for loop, but not as I have it presented. Thanks a bunch!!

You question and example are incomplete.  Read 
https://stackoverflow.com/help/mcve and follow it by adding in the 
missing definitions and printing the result.  For example:

satellite_origin_list = []
satellite_dataread = '''\
hooray, usa
salud3, ussr
panda 33, china
'''.splitlines()
list2 = ['ray', 'and']

for line in satellite_dataread:
         if any(i in line for i in list2):
             line= line.strip()
             satellite, country= line.split(',')
             satellite_origin_list.append(country)

print(satellite_origin_list)

# prints
[' usa', ' china']

Now tell us what you think is wrong with this result, which is exactly 
what I expected.

Note: you might want to unpack lines first and then test either 
satellete or country separately.

-- 
Terry Jan Reedy




More information about the Python-list mailing list