简体   繁体   English

如何在生成元组时获取它的索引?

[英]How to get the index of a tuple as it's being generated?

So, I'm instantiating a class several times using a tuple -- every tuple item is a class instance in the format所以,我使用一个元组多次实例化一个类——每个元组项都是格式中的一个类实例

ClassName(argument 1, ... argument n)

Now, I'd like one of the arguments to be the index of the item in the tuple, but I don't know how to express that in Python.现在,我希望参数之一是元组中项目的索引,但我不知道如何在 Python 中表达它。 I tried using我尝试使用

my_tuple.index(ClassName)

but that didn't work.但这没有用。 Any other ideas?还有其他想法吗?

You can use a list comprehension.您可以使用列表推导。

tuple([ClassName(i, argument 2, ..., argument n) for i in range(however_many_you_want)])

This will create a list which will then be converted into a tuple.这将创建一个列表,然后将其转换为元组。 Here, the first argument is being used as the index in the tuple.在这里,第一个参数被用作元组中的索引。

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

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