LIst Comprehensions: References to the Components

前端 未结 4 1964
眼角桃花
眼角桃花 2021-02-15 14:34

In sum: I need to write a List Comprehension in which i refer to list that is being created by the List Comprehension.

This might not be something you need to do every d

4条回答
  •  有刺的猬
    2021-02-15 14:49

    As far as I know, there is no way to access a list comprehension as it's being built.

    As KennyTM mentioned (and if the order of the entries is not relevant), then you can use a set instead. If you're on Python 2.7/3.1 and above, you even get set comprehensions:

    { some_function(s) for s in raw_data }
    

    Otherwise, a for loop isn't that bad either (although it will scale terribly)

    l = []
    for s in raw_data:
        item = somefunction(s)
        if item not in l:
            l.append(item)
    

提交回复
热议问题