【问题标题】:what is the meaning of * on python? [duplicate]python上的*是什么意思? [复制]
【发布时间】:2017-09-20 02:44:48
【问题描述】:

我有下一个查询。

item = [item.export_simple()
            for item in session.query(Item)
                               .filter(and_(
                                       Item.companyId == company_id,
                                       or_(
                                           True if search == "" else None,
                                           or_(*[Item.name.like('%{0}%'.format(s)) for s in words]),
                                           or_(*[Item.code.like('%{0}%'.format(s)) for s in words])
                                            ))).order_by(Item.name)]

还有这个。

if type == "code":
            src = [Item.code.like('%{0}%'.format(s)) for s in words]
        elif type == "name":
            src = [Item.name.like('%{0}%'.format(s)) for s in words]

 session.query(Item)
                    .filter(and_(
                        Item.companyId == company_id,
                        Item.typeItem == item_type,
                        or_(
                            True if search == "" else None,
                            or_(*src)
                        )))

在这两种情况下,我在 or_() 语句中都有* 运算符,并且两个查询都工作得很好,但我不知道具体原因。 这是referencethis one

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:

    这与 SQLAlchemy 无关。这会将列表解压缩为逗号分隔的参数,并且是一个出色的 Python 功能。它的正式名称为“单星”运算符,但通常称为“splat”运算符。这个:

    a = [1, 2, 3]
    something(*a)
    

    相当于这个:

    something(1, 2, 3)
    

    因此,在您的第一个示例中,它执行列表推导 [Item.name.like('%{0}%'.format(s)) for s in words],然后将其参数解包到 or_ 调用中。

    有关此运算符的更多信息,请参阅Python documentation

    【讨论】:

    • 出于谷歌搜索的目的,我认为重要的是要提到这通常被称为 splat 运算符。
    • 当将 *list 或 *tuple 传递给 something(*a) 时,它们都被强制转换为 something() 内部的元组,这难道不是真的吗?
    • @rp.可以给个代码示例吗?
    • 显示强制的代码在这个问题中:stackoverflow.com/questions/37376674/…
    猜你喜欢
    • 2015-02-13
    • 1970-01-01
    • 2019-03-30
    • 2019-09-12
    • 2015-01-22
    • 2019-04-15
    • 2020-03-26
    • 2019-12-17
    • 2011-12-23
    相关资源
    最近更新 更多