【问题标题】:Convert a list of lists (objects) into a list of strings将列表(对象)列表转换为字符串列表
【发布时间】:2020-07-09 16:29:30
【问题描述】:

有没有办法可以转换这个:

listofadds = [(1, 'fakestreet', 'city', 'ab12 1ab'), (2, 'sillystreet', 'othercity', 'dc12 4ef')]

进入这个:

['1 fakestreet city ab12 1ab', '2 sillystreet othercity dc12 4ef']

到目前为止,我已经能够通过将整数转换为字符串然后连接来转换其中一个:

f = listofadds[0]
h = [str(i) for i in f]
g = ' '
s = g.join((h))
>>> '1 fakestreet city ab12 1ab'

但我不确定如何使用 for 循环成功地为下一个循环以及原始列表中出现的任何其他循环重复此操作!

任何帮助将不胜感激。

【问题讨论】:

    标签: python list for-loop object nested-lists


    【解决方案1】:
    listofadds = [(1, 'fakestreet', 'city', 'ab12 1ab'), (2, 'sillystreet', 'othercity', 'dc12 4ef')]
    new_list = [' '.join([str(i) for i in curr]) for curr in listofadds]
    print(new_list)
    

    【讨论】:

      【解决方案2】:

      这是另一个例子:

      new_list = []
      for object in listofadds:
          element_string = " ".join([str(element) for element in object])
          new_list.append(element_string)
      

      【讨论】:

        猜你喜欢
        • 2010-10-03
        • 1970-01-01
        • 2019-01-17
        • 2018-05-01
        • 1970-01-01
        • 2015-02-25
        • 1970-01-01
        相关资源
        最近更新 更多