简体   繁体   中英

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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