简体   繁体   中英

How risky is using list.index() for getting the index of a set?

I want to find and store the index of an element in a set of strings. Basically, I have a set of strings. If a new string lies in that set, I want it to be allotted the index number. If not, I want to add it to the set, and allot a new index number.

Now, I'm pretty sure I can do this using a dictionary with ease. I was wondering whether I could do the following, however:

s = set(['apple','banana','orange','mango','pineapple'])

if fruit in s:
    print list(s).index(fruit)
else:
    s.add(fruit)
    print list(s).index(fruit)

Will the order of existing elements change if a new element is added, or a new instance of an existing element is added? I've tried it out and it doesn't seem to change, but I wanted to be sure.

Thanks.

Will the order of existing elements change if a new element is added[?]

It can easily change. set s don't have order, and you can't rely on them being ordered by insertion in practice, either:

>>> a = {"b", "c"}
>>> a
set(['c', 'b'])
>>> list(a).index("c")
0
>>> a.add("a")
>>> a
set(['a', 'c', 'b'])
>>> list(a).index("c")
1

It's a bad idea to use indexing on sets. Sets are unordered collection.

You could use a combination of set and list here. Set to keep track of seen items and list to maintain the order of insertion.

>>> lis = []
>>> seen = set()
>>> for x in ['apple','banana','orange']:
    if x not in seen:
        seen.add(x)
        lis.append(x)
...         
>>> if 'banana' in seen:
...     print lis.index('banana')
... else:
...     seen.add('banana')
...     lis.append('banana')
...     print len(lis)-1
...     
1
>>> if 'bar' in seen:
    print lis.index('bar')
else:
    seen.add('bar')
    lis.append('bar')
    print len(lis)-1
...     
3

Risky:

Order is intact:

>>> lis
['apple', 'banana', 'orange', 'bar']

list maintains the order, while list(set) returns items in arbitrary order.

>>> list(seen)
['orange', 'bar', 'apple', 'banana']

Sets are unordered collections, if you build a list from a set you cannot be sure that the elements in the list will always have the same order. It may happen, but it's not guaranteed.

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