【问题标题】:Python: concatenate string variables of a list [duplicate]Python:连接列表的字符串变量[重复]
【发布时间】:2018-06-21 05:47:21
【问题描述】:

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

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

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

print(magicians)

但它返回原始列表:

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

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

【问题讨论】:

    标签: python


    【解决方案1】:

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

    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]
    

    【讨论】:

    • 非常感谢您抽出宝贵时间回答我的愚蠢问题。我只是通过你的问题知道了 enumerate() 函数。您能否在我的问题中进一步解释一下 for 循环下的底层过程?愚蠢的我只是认为 for 循环将遍历列表以选择每个元素并将其分配给魔术师变量。真的谢谢你...
    【解决方案2】:

    列表理解更pythonic

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

    Documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-16
      • 2014-07-20
      • 2018-08-30
      • 2019-10-23
      • 2020-12-30
      • 1970-01-01
      • 2019-05-20
      • 2019-01-05
      相关资源
      最近更新 更多