-1

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.

4

3 回答 3

1

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

It can easily change. sets 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
于 2013-11-10T12:31:07.793 回答
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']
于 2013-11-10T12:31:55.953 回答
0

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.

于 2013-11-10T12:32:19.003 回答