dimanche 5 mai 2019

Where to place If / Else clause in nested list comprehension

I'm using nested list comprehension to find and replace values in a nested list that feeds into a function. I have two different comprehensions. the first [ x for xs in name_list for x in xs ] returns each item in nested list. The second [ new if x == old else x for x in name_list ] replaces old values with new values from a dictionary. My question is, where do I put the second comprehension in the first? Should I even do that? Should I make the second comprehension a second function that uses the first as a parameter?

Here's my code.

# opens text file
with open( 'template.txt', 'r' ) as f:

# reads file into a list
    content = [ line.strip() for line in f ]

# Sample List
# content = ['.topA1', 'green', 'circle']

# makes 4 copies of list
    topA1 = list( content )
    topB1 = list( content )
    topC1 = list( content )
    topD1 = list( content )

# puts copies into a list
name_list = [ topA1, topB1, topC1, topD1 ]

# dictionary of old values to replace
old={ 'old': '.topA1', 'old': '.topAl', 'old': '.topAl', 'old': '.topAl' }

# dictionary of new values
new={ 'new': '.topA1', 'new': '.topB1', 'new': '.topC1', 'new': '.topD1' }

# creates function
def replaced( *name_list, old=None, new=None ):

# returns each item in nested list ( First comprehension)
    return [ x for xs in name_list for x in xs ]

# Second comprehension
#    [ new if x == old else x for x in name_list ]

#calls function
new_words = ( replaced( *name_list, **old, **new ))

#iterates through value
for item in new_words:

#prints each item
    print( "%s" % item )

Aucun commentaire:

Enregistrer un commentaire