简体   繁体   中英

Fastest way to find and add Integers in List in Python

I have a lot of high integers and I want to decrease their processing capacity by adding them to a list and link the integer to the index number of the list.

For example I add the Integer 656853 to a new list. Its Index is 0 now, since it's the first entry. For the next integer I check the list to see if the value already exists. If not, I add the integer to the list. This should be done with multiple integers.

What is the fastest way to find and add integers to a List?

Is it a good idea to sort them, so they are quicker to find?

Use a set (). This will make sure you will have only one entry for given int.

int_set = set()
int_set.add(7)
int_set.add(7)
# there is only one 7 in the int set

unique_list = list(set(huge_list_of_integers))

If you need indexed reference:

for i,num in enumerate(unique_list):
    print(i, num)

Or map to a dict of index:value:

unique_dict = dict(enumerate(set(huge_list_of_integers)))
for i,v in unique_dict.items():
    print(i, v)

Dict by value:index:

unique_dict = {v:i for i,v in enumerate(set(huge_list_of_integers))}
for v,i in unique_dict.items():
    print(v,i)

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