user4358655
user4358655

Reputation:

Matching lists indexes

I have two lists,they has same elements.

a=[1,2,3,4,5,6,7,8,9]
b=[1,2,3,4,5,6,7,8,9]

If I write this:

a[::]==b[::]
>>>True

So that means all of elements indexes are equal. But I want to shuffle b till b's indexes are different than a's.

I tried this:

import random
while a[::]==b[::]:
    random.shuffle(b)

I thought it will shuffle b till all of the indexes are different,but its not what I expected.All the time at least one element has same index.What can I do ?

Upvotes: 2

Views: 49

Answers (2)

Barry
Barry

Reputation: 302708

a[::] == b[::] checks that all the indices are equal. You want to keep shuffling as long as any index is equal. Which is to say:

while any(a[i] == b[i] for i in xrange(len(a)):
    random.shuffle(b)

Upvotes: 0

DSM
DSM

Reputation: 352979

a[::] == b[::] -- or simply a == b -- checks to see whether all the elements are equal, which is why your while is ending (probably on the very first step).

You want something different, namely that none of them are equal, IOW that not any are equal.

We can use any and zip to implement this condition:

>>> a=[1,2,3,4,5,6,7,8,9]
>>> b=[1,2,3,4,5,6,7,8,9]
>>> import random
>>> while any(x==y for x,y in zip(a,b)):
...     random.shuffle(b)
...     
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> b
[6, 5, 1, 2, 7, 8, 9, 4, 3]

Upvotes: 1

Related Questions