社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何在python中基于另一个列表重新排列列表

alvin Christianto • 5 年前 • 1514 次点击  

我想根据以下条件重新排列列表(或创建新列表):

fixedList = ['116','117','114','99','102','101','95']

unorderedList = ['99','116','117']

我想列个新单子,比如:

newList = ['116','117','99'] .

新列表 基于 ,并且排序基于 固定列表

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/57126
文章 [ 5 ]  |  最新文章 5 年前
Nithin R
Reply   •   1 楼
Nithin R    5 年前

import numpy as np

fixedList = ['116','117','114','99','102','101','95']
unorderedList = ['99','116','117']

# isin returns a boolean array of the same shape as element 
# that is True where an element of unorderedList is in fixedList and False otherwise.

mask = np.isin(np.array(fixedList), np.array(unorderedList))

#Now form new list using mask
newlist = (np.array(fixedList)[mask]).tolist()

现在新列表包含以下内容

参考 https://docs.scipy.org/doc/numpy/reference/generated/numpy.isin.html

Sayed Hussain Mehdi
Reply   •   2 楼
Sayed Hussain Mehdi    5 年前
def intersection(lst1, lst2): 
    lst3 = [value for value in lst1 if value in lst2] 
    return lst3

fixedList = ['116','117','114','99','102','101','95']
unorderedList = ['99','116','117']

print( intersection(fixedList,unorderedList)) 

https://www.geeksforgeeks.org/python-intersection-two-lists/

fmarm
Reply   •   3 楼
fmarm    5 年前

[el for el in fixedList if el in unorderedList]

结果如期而至

['116', '117', '99']
Alexander Lekontsev
Reply   •   4 楼
Alexander Lekontsev    5 年前

像这样的东西。

sorted(unorderedList, key=fixedList.index)
jarmod
Reply   •   5 楼
jarmod    5 年前

使用自定义排序,其中要排序的键是固定列表中的索引,例如:

fixedList = ['116','117','114','99','102','101','95']
unorderedList = ['99','116','117']
newList = sorted(unorderedList, key=lambda x:fixedList.index(x))

输出为:

['116', '117', '99']