【问题标题】:How can I let my output be printed in a single string instead of seperate letters?如何让我的输出以单个字符串而不是单独的字母打印?
【发布时间】:2021-11-09 13:54:56
【问题描述】:

所以我编写了这段代码来获取网格中的每一行

def rows(test):
    r = []
    for x in test:
        r.append(x)
    return str(r)

顺便说一句,网格是这样的

test = [["r","a","w","b","i","t"],
        ["x","a","y","z","c","h"],
        ["p","q","b","e","i","e"],
        ["t","r","s","b","o","g"],
        ["u","w","x","v","i","t"],
        ["n","m","r","w","o","t"]]

在运行rows(test) 之后,我明白了

[['r', 'a', 'w', 'b', 'i', 't'], ['x', 'a', 'y', 'z', 'c', 'h'], ['p', 'q', 'b', 'e', 'i', 'e'], ['t', 'r', 's', 'b', 'o', 'g'], ['u', 'w', 'x', 'v', 'i', 't'], ['n', 'm', 'r', 'w', 'o', 't']]

但我希望它是

 [['rawbit','xayzch','pqbeie','trsbog', 'uwxvit', 'nmrwot']

我应该改变什么??

【问题讨论】:

    标签: python string list tuples


    【解决方案1】:

    使用.join:

    def rows(test):
        r = list()
        for row in test:
            r.append("".join(row))
        return r
    
    >>> rows(test)
    ['rawbit', 'xayzch', 'pqbeie', 'trsbog', 'uwxvit', 'nmrwot']
    

    【讨论】:

      【解决方案2】:

      您可以使用''.join(),如下所示:

      >>> lst = [['r', 'a', 'w', 'b', 'i', 't'], ['x', 'a', 'y', 'z', 'c', 'h'], ['p', 'q', 'b', 'e', 'i', 'e'], ['t', 'r', 's', 'b', 'o', 'g'], ['u', 'w', 'x', 'v', 'i', 't'], ['n', 'm', 'r', 'w', 'o', 't']]
      >>> list(map("".join, lst))
      #OR
      >>> [''.join(l) for l in lst]
      ['rawbit', 'xayzch', 'pqbeie', 'trsbog', 'uwxvit', 'nmrwot']
      

      如果你想function:

      def rows(test):
          # return [''.join(t) for t in test]
          # Or
          return list(map(''.join, test))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-02-09
        • 2011-12-08
        • 1970-01-01
        • 1970-01-01
        • 2015-07-30
        • 1970-01-01
        • 1970-01-01
        • 2015-07-30
        相关资源
        最近更新 更多