【问题标题】:Adding whitespaces around each element of a list of lists python在列表 python 列表的每个元素周围添加空格
【发布时间】:2022-11-14 18:48:40
【问题描述】:

我想在列表列表中的每个元素周围添加空格

data = [["hello", "world"], ["python", "is", "cool"]]
-->
data = [[" hello ", " world "], [" python ", " is ", " cool "]]
data_new = ["hello world", "python is cool"]
data_new2 = [x.split(" ") for x in data_new]
--> [["hello", "world"], ["python", "is", "cool"]]
data_new2 = [' {0} '.format(word) for elem in data_new2 for word in elem]
print(data_new2[:10])
--> [" hello ", " world ", " python ", " is ", " cool "]

【问题讨论】:

    标签: python format list-comprehension whitespace


    【解决方案1】:

    你不需要拆分,使用嵌套列表理解(这里有一个 f-string):

    data = [["hello", "world"], ["python", "is", "cool"]]
    
    data2 = [[f' {x} ' for x in l] for l in data]
    

    输出:

    [[' hello ', ' world '], [' python ', ' is ', ' cool ']]
    

    替代输入:

    data = ["hello world", "python is cool"]
    
    data2 = [[f' {x} ' for x in s.split()] for s in data]
    

    【讨论】:

    • 在这种情况下,输入列表是什么样的 - ["hello world", "python is cool"] 或 [["hello", "world"], ["python", "is", "cool"]]?
    • 查看备选方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-09
    • 2018-02-25
    • 2023-03-21
    相关资源
    最近更新 更多