简体   繁体   English

如何将其转换为Python列表推导?

[英]How Do I Turn This Into A Python List Comprehension?

I'd like to make this more efficient but I can't figure out how to turn this into a python list comprehension. 我想提高效率,但是我不知道如何将其转换为python列表理解。

coupons = []
for source in sources:
    for coupon in source:
        if coupon.code_used not in coupons:
            coupons.append(coupon.code_used)

您无法访问当前创建的列表,但是如果顺序不重要,则可以使用set

coupons = set(coupon.code_used for source in sources for coupon in source)
used_codes = set(coupon.code_used for source in sources for coupon in source)

I'm going to assume that the order of the resulting list is unimportant, because then we can just use a set to eliminate duplicates. 我将假设结果列表的顺序并不重要,因为这样我们就可以使用集合来消除重复项。

coupons = list(set(coupon.code_used for source in sources for coupon in source))

This uses a generator expression, with the for clauses appearing in the same order as in the nested loop, to extract all the codes. 它使用生成器表达式(其中for子句以与嵌套循环中相同的顺序出现)提取所有代码。 The set keeps only unique codes, and list creates a list (arbitrarily ordered) from the set. set仅保留唯一的代码,而list从集合list创建一个列表(任意排序)。

coupons = {x for x in (y.code_used for y in coupon for coupon in sources)}

您实际上正在寻找set

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM