【问题标题】:How to add a for loop inside .join() in python如何在python中的.join()中添加一个for循环
【发布时间】:2020-04-28 08:29:24
【问题描述】:

我发现有人在代码战中做类似的事情。但对我来说,它永远不会起作用。有人可以告诉我这段代码有什么问题以及我应该做些什么来纠正它。 提前谢谢!

P.S.:我知道在外面写一个 for 循环可以解决这个问题,但我希望我的代码简洁明了:D 编辑:谢谢各位。成功了!

names = ["Alexa","Siri","Cortana"]
print(" ".join("Hello there ",(i for i in names)))

这里是固定代码:

names = ["Alexa","Siri","Cortana"]
print("".join([f"Hello there {i}!\n" for i in names]))

【问题讨论】:

    标签: python list function for-loop join


    【解决方案1】:

    您需要将值格式化为要连接的字符串:

    names = ["Alexa","Siri","Cortana"]
    print(" ".join(f"Hello there {i}" for i in names))
    

    输出:

    Hello there Alexa Hello there Siri Hello there Cortana
    

    【讨论】:

      【解决方案2】:

      试试这个:-

      names = ["Alexa","Siri","Cortana"]
      
      print(', '.join(['Hello there ' + i for i in names]))
      

      输出:-

      'Hello there Alexa,  Hello there Siri,  Hello there Cortana'
      

      【讨论】:

      • 如果您想要正确数量的逗号,请将逗号放在连接字符串中:', '.join
      • 并删除另一个逗号。
      • 也许你知道,但我不得不提到str.join 使用列表理解比生成器表达式更快,+1
      【解决方案3】:

      首先,这不是一个 for 循环,这是一个生成器表达式(在您的情况下)或 list/dict/set 理解。其次,str.join 只接受一个参数,而您提供了两个参数 - 您希望输出为:Hello there Alexa Hello there Siri Hello there Cortana 还是 Hello there Alexa Siri Cortana?根据答案,代码可能是:

      print(" ".join("Hello there " + x for x in names))
      

      print("Hello there " + " ".join(names))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-08-23
        • 2017-04-10
        • 2015-01-29
        • 1970-01-01
        • 2020-05-11
        • 2020-04-04
        • 1970-01-01
        相关资源
        最近更新 更多