我有一个未排序的数字列表,带有偶数和奇数。我需要按排序顺序分隔奇数和偶数。
例如:
List = [5,6,4,7,11,14,12,1,3]
预期输出 :
[4,6,12,14,1,3,5,7,11]
我的程序是分离奇数和偶数。
L = [5,6,4,7,11,14,12,1,3]
def segregateEvenOdd(L):
left,right = 0,len(L)-1
while left < right:
while (L[left]%2==0 and left < right):
left += 1
while (L[right]%2 == 1 and left < right):
right -= 1
if (left < right):
L[left],L[right] = L[right],L[left]
left += 1
right = right-1
print segregateEvenOdd(L)
output : [12, 6, 4, 14, 11, 7, 5, 1, 3]
我正在尝试使用插入排序对列表进行排序,无法获得正确的输出。任何可以轻松排序的方法<</p>
使用 list.sort/sorted 的关键函数:
>>> list(sorted(lst, key=lambda x: [x % 2, x]))
[4, 6, 12, 14, 1, 3, 5, 7, 11]
将偶数n
映射到值[0, n]
,奇数n
映射到值[1, n]
,因此偶数根据列表项的自然顺序排在第一位,即 [0, ...]
先于[1, ...]
.
添加到@fferi的答案.
如果你想要偶数后跟奇数,每个按升序排列,请执行以下操作:
>>> lst=range(10)
>>> sorted(lst, key = lambda x:(x%2, x))
[0, 2, 4, 6, 8, 1, 3, 5, 7, 9]
奇数后跟偶数,每个按升序排列
>>> sorted(lst, key = lambda x:(not x%2, x))
[1, 3, 5, 7, 9, 0, 2, 4, 6, 8]
偶数后跟奇数,每个按降序排列
>>> sorted(lst, key = lambda x:(not x%2, x), reverse=True)
[8, 6, 4, 2, 0, 9, 7, 5, 3, 1]
奇数后跟偶数,每个按降序排列
>>> sorted(lst, key = lambda x:(x%2, x), reverse=True)
[9, 7, 5, 3, 1, 8, 6, 4, 2, 0]
Short_list =[5,7,3,2,8,1,0,10,9,4,6]
def sort_list(my_list):
even_list = []
odd_list = []
for i in my_list:
if i % 2 == 0:
even_list.append(i)
else:
odd_list.append(i)
even_list.sort(),odd_list.sort()
even_list.extend(odd_list)
return even_list
print(sort_list(Short_list))
[0, 2, 4, 6, 8, 10, 1, 3, 5, 7, 9]
简单使用列表理解基础
>>> arr = [5,6,4,7,11,14,12,1,3]
>>> evens = sorted([e for e in arr if e % 2 ==0])
>>> odds = sorted([e for e in arr if e % 2 !=0])
>>> print(evens + odds)
[4, 6, 12, 14, 1, 3, 5, 7, 11]
我们可以首先对 n%2
(n 模 2( 进行排序,奇数为 0,偶数为 1,然后对数字本身进行排序:
L = [5,6,4,7,11,14,12,1,3]
out = sorted(L, key = lambda n:(n%2, n))
print(out)
# [4, 6, 12, 14, 1, 3, 5, 7, 11]
我们用作键的元组首先根据它们的第一个项目进行排序,然后根据它们的第二个项目进行排序。
它也适用于负数...
列出偶数和赔率列表,然后合并:
lst = [5,6,4,7,11,14,12,1,3]
even = sorted([i for i in lst if i%2 == 0])
odd = sorted([i for i in lst if i%2])
print(even + odd)
或者使用 filter
, lambda
:
lst = [5,6,4,7,11,14,12,1,3]
lst.sort()
even = list(filter(lambda x: not x%2, lst))
odd = list(filter(lambda x: x%2, lst))
print(even + odd)
愿意使用第三方库,则可以将布尔索引与numpy
一起使用。
numpy.lexsort
以相反的方式排序,即它在A
之前考虑A % 2
:
import numpy as np
A = np.array([4,6,12,14,1,3,5,7,11])
res = A[np.lexsort((A, A % 2))]
# [ 4 6 12 14 1 3 5 7 11]
相关:为什么是NumPy而不是Python列表?
避免使用外部库,我建议您这样做:
def even_odd_sort(list):
evens=[]
odds=[]
for i in list:
if(i%2==0):
evens.append(i)
else:
odds.append(i)
evens.sort()
odds.sort()
return evens+odds
<</div>
div class="one_answers"> 一个简单的解决方案:
import numpy as np
l = [5,6,4,7,11,14,12,1,3]
l_sort = np.sort(l) #sorting elements of the list
evens = list(filter(lambda x: x%2==0, l_sort)) #extract even elements
odds = list(filter(lambda x: x%2!=0, l_sort)) #extract odd elements
out = evens + odds
该过程涉及在单独的临时列表中将值拆分为偶数和奇数,然后按升序对它们进行数字排序,最后将所有值放在一个列表中。下图显示了 C# 上的两个项目,一个包含所有过程,而第二个更实用,但该过程适用于你的项目。
步骤:
- 将原始列表一分为二,一个用于偶数,另一个用于赔率。
- 对于这两个列表,按升序对它们进行排序。
- 现在将两个列表合并到一个列表中。
图-1
图-2
图-3
图-4
- 这就是所有的 C# 代码,我希望这有所帮助,迟到总比没有好:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
combodata1();
}
public void combodata1() {
combo1.DataSource = new String[] {"5","10","15","20","25","30","35","40"};
}
private void button2_Click(object sender, EventArgs e)
{
generate();
}
List<String> li1 = new List<String>();
List<String> li2 = new List<String>();
List<String> li3 = new List<String>();
List<String> li4 = new List<String>();
List<String> li5 = new List<String>();
public void generate() {
li1.Clear();
int r = Convert.ToInt32(combo1.SelectedValue)-1;
Random ran = new Random();
for(int i=0;i<=r;i++){
int num1 = ran.Next(100);
li1.Add(Convert.ToString(num1));
}
lista1.DataSource = null;
lista1.DataSource = li1;
}
private void button1_Click(object sender, EventArgs e)
{
String te1 = data1.Text;
if (te1.Equals("") == false)
{
add();
}
else {
MessageBox.Show("- You need to add integer numbers only, empty space or letters are not allowed.","Message");
}
}
public void add() {
String dato = data1.Text;
li1.Add(dato);
lista1.DataSource = null;
lista1.DataSource = li1;
data1.Text = "";
}
private void button3_Click(object sender, EventArgs e)
{
int n = lista1.Items.Count;
if(n>0){
split();
}
else {
MessageBox.Show("- Original List must present values.","Message");
}
}
public void split() {
int n = lista1.Items.Count-1;
for (int i = 0; i <= n;i++){
double a = Convert.ToDouble(li1.ElementAt(i));
double b = (a / 2);
double c = b - Math.Floor(b);
if (c == 0){
li2.Add(Convert.ToString(a));
}
else {
li3.Add(Convert.ToString(a));
}
}
sort_evenly();
}
public void sort_evenly() {
int w = li2.Count;
if (w > 0)
{
int n = li2.Count - 1;
int a = Convert.ToInt32(li2.ElementAt(0));
for (int i = 1; i <= n; i++)
{
int b = Convert.ToInt32(li2.ElementAt(i));
if (a > b) { a = b * 1; }
if (a < b) { a = a * 1; }
}
li4.Add(Convert.ToString(a));
li2.Remove(Convert.ToString(a));
sort_evenly();
}
else {
sort_oddly();
}
}
public void sort_oddly() {
int w = li3.Count;
if (w > 0)
{
int n = li3.Count - 1;
int a = Convert.ToInt32(li3.ElementAt(0));
for (int i = 1; i <= n; i++)
{
int b = Convert.ToInt32(li3.ElementAt(i));
if (a < b) { a = a * 1; }
if (a > b) { a = b * 1; }
}
li5.Add(Convert.ToString(a));
li3.Remove(Convert.ToString(a));
sort_oddly();
}
else {
sortedlist();
}
}
String even = "";
String odd = "";
String result = "";
public void sortedlist() {
even = "";
odd = "";
result = "";
int n = li4.Count-1;
int k = li5.Count-1;
for(int i=0;i<=n;i++){
String hyphen = "-";
if(i==n){hyphen="";}
even = even + Convert.ToString(li4.ElementAt(i)) + hyphen;
}
for(int i=0;i<=k;i++){
String hyphen = "-";
if(i==k){hyphen="";}
odd = odd + Convert.ToString(li5.ElementAt(i)) + hyphen;
}
result = even + "-" + odd;
res1.Text = result;
li2.Clear();
li3.Clear();
li4.Clear();
li5.Clear();
}
private void button4_Click(object sender, EventArgs e)
{
clear();
}
public void clear() {
li2.Clear();
li3.Clear();
li4.Clear();
li5.Clear();
res1.Text = "";
}
private void button5_Click(object sender, EventArgs e)
{
clearall();
}
public void clearall() {
data1.Text = "";
li1.Clear();
li2.Clear();
li3.Clear();
li4.Clear();
li5.Clear();
lista1.DataSource = null;
res1.Text = "";
}
}
}
在python中:
data = [100, 1, 2, 3, 4, 5, 6, 65, 89, 7, 8, 9, 10]
print(sorted([e for e in data if e % 2 == 0]) + sorted([e for e in data if e % 2 != 0]))
我的方法(长(:
l=[4,1,2,3]
# separate odd and even position elements
ev=[]
odd=[]
for i in range(len(l)):
if i%2==0:
ev.append(l[i])
else:
odd.append(l[i])
# sort them
newev = sorted(ev)
newodd= sorted(odd, reverse=True)
# combine them
comb=list(zip(newev, newodd))
# append according to the order
out=[]
for i, v in enumerate(op):
out.append(v[0])
out.append(v[1])
print(out)
# [2,3,4,1]