Python:连接列表的字符串变量

时间:2018-01-11 19:50:24

标签: python

我正在尝试修改Python中列表的所有元素:

magicians = ['harry potter', 'scamander', 'snape']

for magician in magicians:      
    magician = 'the Great ' + magician

print(magicians)

但它返回原始列表:

['harry potter', 'scamander', 'snape']

请您一步一步地向我解释一下吗? 这可能是你见过的一个非常愚蠢的问题。我真的很抱歉。

2 个答案:

答案 0 :(得分:4)

您只是在改变循环范围中的元素。相反,使用元素索引重新分配:

magicians = ['harry potter', 'scamander', 'snape']

for i, magician in enumerate(magicians):      
   magician = 'the Great ' + magician
   magicians[i] = magician

print(magicians)

输出:

['the Great harry potter', 'the Great scamander', 'the Great snape']

但是,使用列表理解要短得多:

magicians = ['harry potter', 'scamander', 'snape'] 
new_magicians = ['the Great {}'.format(i) for i in magicians]

输出:

['the Great harry potter', 'the Great scamander', 'the Great snape']

在问题的范围内,甚至不需要循环:

final_data = ("the Great {}*"*len(magicians)).format(*magicians).split('*')[:-1]

答案 1 :(得分:0)

列表理解更多是 pythonic

magicians = ['harry potter', 'scamander', 'snape']

great_magicians = ['the Great {}'.format(magician) for magician in magicians]

Documentation