lauriane.g
lauriane.g

Reputation: 337

How to shuffle (not randomly) a list in Python?

I analyze information that I retrieve from csv files that are in a folder. I read these files in alphabetical order and build two lists from what I read:

l, which is the list that retrieves the names of the files (without the extension).

resu, which is the list containing the information I'm interested in these files.

l = ['a','b','c','d','e','f']
resu = [150,43,35,49,53,27]

I draw plt.bar from this information and I would like to draw them in a certain order to be able to interpret them better.

I would like to put the files in this order : 'a','b','d','f','e','c'.

I have written :

(l[2],l[3],l[4],l[5])=(l[3],l[5],l[4],l[2])
(resu[2],resu[3],resu[4],resu[5])=(resu[3],resu[5],resu[4],resu[2])

Is there a way to do this more easily and quickly ? I have thought of using the list of new item indexes : [0,1,3,5,4,2] but I haven't found how I could use this.

Upvotes: 0

Views: 98

Answers (4)

jupiterbjy
jupiterbjy

Reputation: 3550

Listcomp with list.index?

>>> l = ['a','b','c','d','e','f']
>>> change = ['a','b','d','f','e','c']
>>> resu = [150,43,35,49,53,27]

>>> [resu[l.index(idx)] for idx in change]

[150, 43, 49, 27, 53, 35]

Upvotes: 0

jimakr
jimakr

Reputation: 604

You can use an iterator with map

order = [0,1,3,5,4,2]
resu = map(l.__getitem__, order)

most simple things that accept a list will accept the iterator as an input, if you need a list specifically you can add the list() over the map like this

resu = list(map(l.__getitem__, order))

Upvotes: 0

Wups
Wups

Reputation: 2569

Generic function to reorder any amount of lists:

def reorder(order, *lists):
    result = []
    for l in lists:
        result.append([])
        for i in order:
            result[-1].append(l[i])
    return result

Usage:

l, resu = reorder([0,1,3,5,4,2], l, resu)

Upvotes: 0

Thomas
Thomas

Reputation: 182083

One way, which is similar to your approach but less repetitive:

>>> order = ['a','b','d','f','e','c']
>>> [resu[l.index(key)] for key in order]
[150, 43, 49, 27, 53, 35]

You can do the same for l but you'll just get order back, so you might as well use order directly.


A nicer way is to convert your data to a dictionary first:

>>> d = dict(zip(l, resu))
>>> d
{'a': 150, 'b': 43, 'c': 35, 'd': 49, 'e': 53, 'f': 27}
>>> [d[key] for key in order]
[150, 43, 49, 27, 53, 35]

Upvotes: 1

Related Questions