Python:在列表理解本身中指的是列表理解吗? [英] Python: Referring to a list comprehension in the list comprehension itself?

查看:42
本文介绍了Python:在列表理解本身中指的是列表理解吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个想法刚刚浮现在我的脑海.出于任何原因说出您想通过Python中的列表理解来获取列表的唯一元素的原因.

This thought just came to my mind. Say for whatever reason you wanted to get the unique elements of a list via a list comprehension in Python.

[i,如果我在{created_comprehension}中为i,否则在[1、2、1、2、3]中为i为0

[1、2、0、0、3]

我不知道,我并没有真正的目的,但是如果可以在创建理解内容时提及它,那将是很酷的事情.

I dunno, I don't really have a purpose for this but it'd be cool if it was possible to refer to the comprehension as it's being created.

(例如如何删除重复项使用列表理解功能从列表中获取信息?是一个类似的问题)

(e.g. How to remove duplicate items from a list using list comprehension? is a similar question)

推荐答案

免责声明:这纯粹是我的推测,我没有数据可以备份

Disclaimer: this is purely speculation on my part, and I don't have data to back it up

我认为您无法在构建列表理解时参考它.在将列表绑定到变量名之前,Python首先必须创建列表,分配内存或它,并向其中添加元素.因此,我认为如果您尝试引用该列表,则最终会得到 NameError,而它是在 list-comp 中构建的

I don't think you can refer to a list comprehension as it is being built. Python will first have to create the list, allocate memory or it, and add elements to it, before it binds it to a variable name. Therefore, I think you'll end up with a NameError if you try to refer to the list, while it's being built in a list-comp

因此,您最终可能想要一个 set 来保存您的唯一身份,然后从那里建立您的列表(哦,天哪!这很hacky):

You might ultimately, therefore, want a set to hold your uniques, and build your list from there (Oh God! this is hacky):

In [11]: L = [1, 2, 1, 2, 3]

In [12]: s = set(L)

In [13]: answer = [sub[0] for sub in [(i,s.remove(i)) if i in s else (0,0) for i in L]]

In [14]: answer
Out[14]: [1, 2, 0, 0, 3]

In [15]: s
Out[15]: set()

这篇关于Python:在列表理解本身中指的是列表理解吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆