嵌套列表推导中If / Else子句的放置位置

时间:2019-05-05 21:35:22

标签: python list if-statement nested list-comprehension

我正在使用嵌套列表推导来查找和替换嵌套中的值 提供功能的列表。我有两种不同的理解。第一个 [name列表中xs x中xs中xs] 返回嵌套列表中的每个项目。第二个 [如果x == old,则为new,否则name_list中的x用于x] ,将旧值替换为词典中的新值。我的问题是,我将第二个理解放在哪里?我应该这样做吗?我应该将第二个理解作为使用第一个作为参数的第二个函数吗?

这是我的代码。

# 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 )

0 个答案:

没有答案