打印索引并在列表理解中执行逻辑
我有一个非常大的列表,在处理过程中,我想知道我在此过程中使用的索引。
一个简单的示例:
l = ['a','b','c']
[ print(i), char.capitalize() for i,char in enumerate(l)]
但是在这里i
尚未定义。是否可以在列表理解中打印和运行一些逻辑?
更新:循环似乎是正常的方式。仅供参考,我的动机是使用asyncio.gather
,我只在列表中看到示例,例如
async def gather():
await asyncio.gather(*[slowtask() for _ in range(10)])
I have a really large list and while processing it I want to know which index I am on during the process.
A simple example:
l = ['a','b','c']
[ print(i), char.capitalize() for i,char in enumerate(l)]
But here i
is not defined. Is it possible to print and run some logic in list comprehension?
Update: Seems normal for loop is the way. fyi, my motivation is to use asyncio.gather
, for which I've only seen examples in list comprehension, e.g.
async def gather():
await asyncio.gather(*[slowtask() for _ in range(10)])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
所有评论都很好,但您必须考虑打印功能是操作系统中的“ IO”操作,并且非常慢。如果您的列表太大,则此功能使您的代码非常慢。
我认为,由于长期运行,您想查看列表的索引。
如果是真的,我建议您从Pandas软件包中使用。将您的列表转换为PANDAS系列,并从PANDAS方法中使用进行计算。熊猫非常非常快,可以优化您的计算。
All of the comment are good but you must consider that print function is an "io" operation in operation systems and is very slow. If your list is too big, this function make your code very slow.
I think that because of long runtime you want to see the index of your list.
If it is true, I advise you to use from pandas package. Convert your list to a pandas series and use from pandas methods for your computation. Pandas is very very fast and optimize your computation.