【问题标题】:Building up a string using a list of values使用值列表构建字符串
【发布时间】:2015-11-12 20:46:37
【问题描述】:

我想填写一个具有特定格式的字符串。当我只有一个值时,构建它很容易:

>>> x = "there are {} {} on the table.".format('3', 'books')
>>> x
'there are 3 books on the table.'

但是如果我有一长串对象怎么办

items =[{'num':3, 'obj':'books'}, {'num':1, 'obj':'pen'},...]

我想以完全相同的方式构造句子:

There are 3 books and 1 pen and 2 cellphones and... on the table

鉴于我不知道列表的长度,我怎么能做到这一点?使用format 可以轻松构造字符串,但我必须事先知道列表的长度。

【问题讨论】:

    标签: python string python-3.x


    【解决方案1】:

    使用str.join() calllist comprehension* 来构建对象部分:

    objects = ' and '.join(['{num} {obj}'.format(**item) for item in items])
    

    然后将其插入到完整的句子中:

    x = "There are {} on the table".format(objects)
    

    演示:

    >>> items = [{'num': 3, 'obj': 'books'}, {'num': 1, 'obj': 'pen'}, {'num': 2, 'obj': 'cellphones'}]
    >>> objects = ' and '.join(['{num} {obj}'.format(**item) for item in items])
    >>> "There are {} on the table".format(objects)
    'There are 3 books and 1 pen and 2 cellphones on the table'
    

    *可以使用generator expression,但是str.join()调用a list comprehension happens to be faster

    【讨论】:

    • Martijn,为什么将列表推导而不是生成器表达式作为str.join 的参数?
    • @Robᵩ 因为join 会自行将生成器表达式转换为列表。通过将生成器表达式传递给join,您将强制join 完成这项工作!
    • @Robᵩ:我总是被问到这个问题,我总是在 Raymond 的公开链接中编辑如何更快地使用列表组合。
    猜你喜欢
    • 1970-01-01
    • 2016-04-06
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 2014-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多