简体   繁体   English

如何在 Python 中混洗(而不是随机)列表?

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

I analyze information that I retrieve from csv files that are in a folder.我分析从文件夹中的 csv 文件中检索到的信息。 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). l ,这是检索文件名称的列表(不带扩展名)。

resu , which is the list containing the information I'm interested in these files. resu ,这是包含我对这些文件感兴趣的信息的列表。

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.我从这些信息中绘制 plt.bar 并且我想按特定顺序绘制它们以便能够更好地解释它们。

I would like to put the files in this order : 'a','b','d','f','e','c' .我想按以下顺序放置文件: '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.我曾想过使用新项目索引列表: [0,1,3,5,4,2]但我还没有找到如何使用它。

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.你可以对l做同样的事情,但你只会得到order ,所以你不妨直接使用order


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]

Listcomp with list.index ? Listcomp 与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]

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)

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接受列表的最简单的事情将接受迭代器作为输入,如果您特别需要一个列表,您可以像这样在地图上添加list()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM