如何对奇数进行排序

how to sort odd numbers

提问人:SHARDloh 提问时间:7/9/2023 最后编辑:ndc85430SHARDloh 更新时间:7/12/2023 访问量:41

问:

我有两个清单: 一个人拥有所有给定的数字 第二个只有第一个列表的奇数

例如:

def sort_array(array):
    odds = array
    
    for x in range(len(odds)):
        if (odds[x] % 2) != 0:
            odds[x] = None
            
    
    
    #return final list

我想对第二个列表进行排序(保存索引),然后反转(同时保存索引) 最后我想返回组合列表

python-3.x 列表 arraylist

评论

1赞 ekhumoro 7/9/2023
你的问题到底是什么?您只是列出了一些要求,而没有做出任何真正的努力来自己找到解决方案。SO 不是代码编写服务。
0赞 Ben the Coder 7/9/2023
请澄清您的具体问题或提供其他详细信息,以准确说明您的需求。正如目前所写的那样,很难确切地说出你在问什么。

答:

1赞 PW1990 7/9/2023 #1
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
aa = list(reversed(sorted([x for x in a if x % 2 != 0])))
b = [] 

for num in a:
    b.append([num, a.index(num)])  # b will be a list of tuples "a" with index attached.

我不知道你真正想要的最终结果是什么,但这里有一些你需要的东西的答案。

0赞 Alain T. 7/12/2023 #2

无需存储/操作索引。在推导式中对排序的奇数值使用迭代器,在偶数项和下一个(排序的)奇数值之间进行选择:

def sortOdds(array):
    odds = reversed(sorted(n for n in array if n%2))
    return [next(odds) if n%2 else n for n in array]

A = [1,3,4,6,5,8,9,7]
R = sortOdds(A)

print(R)

[9, 7, 4, 6, 5, 8, 3, 1]