【问题标题】:Python, reduce list of string doesn't work with newline?Python,减少字符串列表不适用于换行符?
【发布时间】:2022-12-02 22:58:16
【问题描述】:

我尝试使用 reduce 函数将字符串列表组合到字符串,但它不起作用。无论如何,我更喜欢使用 reduce 函数,我该如何解决这个问题?

>> reduce(lambda x, y: x + y + "\n", ["dog", "cat"])
# this doesn't work
# dogcat
>> "\n".join(["dog", "cat"])
# this works
# dog
# cat

【问题讨论】:

  • 当然不行。您只在末尾添加一个新行。你可能是说x + '\n' + y
  • @mousetail 有用哇谢谢!
  • @mousetail 嗨! :)

标签: python


【解决方案1】:

join的目的,就是把元素放在每一个之间

reduce(lambda x, y: x + "
" + y, ["dog", "cat"])

【讨论】:

    【解决方案2】:
    ###################### METHOD 1 ######################
    
    strings = ["This", "is", "a", "list", "of", "strings"]
    
    # join the strings using lambda
    joined = lambda strings: "
    ".join(strings)
    print(joined(strings))
    
    ###################### METHOD 2 ######################
    
    mylist = ["a", "b", "c", "d", "e"]
    
    # use list comprehension to join the list of strings
    mystring = "
    ".join([str(x) for x in mylist])
    print(mystring)
    
    strings = ["This", "is", "a", "list", "of", "strings"]
    
    ###################### METHOD 3 ######################
    import functools
    list_of_strings = ["a", "b", "c"]
    print(functools.reduce(lambda x, y: x + "
    " + y, list_of_strings))
    

    【讨论】:

    • 你的第二种方法就像第一种方法一样,但你不必要地添加 str(x) 即使列表已经包含字符串。
    猜你喜欢
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-22
    • 1970-01-01
    • 2015-01-30
    • 2018-06-21
    • 2022-06-29
    相关资源
    最近更新 更多