在奇数和偶数隔离列表中对奇数和偶数进行排序/分组

时间:2018-04-16 07:46:12

标签: python sorting

我有一个带有偶数和奇数的未排序数字列表。我需要按排序顺序隔离奇数和偶数。

例如:

$(function() {

    $("#button1").click(function(){
        location.reload();
    })

  switch($.session.get("stat")){
    case "":
      $.session.set("stat", "dis");
      $("#button2").prop("disabled",false);
      break;
    case "dis":
      $.session.set("stat", "");
      $("#button2").prop("disabled",true);
      break;
  }


});

预期产出:

List = [5,6,4,7,11,14,12,1,3]

我的程序是将奇数和偶数分开。

[4,6,12,14,1,3,5,7,11]

我正在尝试使用插入排序对列表进行排序,无法获得正确的输出。任何方式轻松排序

10 个答案:

答案 0 :(得分:4)

使用" smart" list.sort / sorted的关键功能:

>>> list(sorted(lst, key=lambda x: [x % 2, x]))
[4, 6, 12, 14, 1, 3, 5, 7, 11]

将偶数数字映射到值[0, n],将奇数映射到值[1, n],以便偶数数字按照自然顺序排在第一位。

答案 1 :(得分:2)

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]

答案 2 :(得分:1)

我们可以先对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]

我们用作键的元组首先根据它们的第一个项目进行排序,然后再按照它们的第二项进行排序。

它也适用于负数......

答案 3 :(得分:0)

制作一个evens列表和赔率列表,然后合并:

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)

或使用filterlambda

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)

答案 4 :(得分:0)

只需使用列表理解基础

>>> 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]

答案 5 :(得分:0)

一个简单的解决方案:

public void getParticularBook(String nameOfBook){
    String bookDetails = "";
    Iterator<Book> iterator = allBooks.iterator();
    while(iterator.hasNext()) {
        Book b = iterator.next();
        if(b.getTitle().equalsIgnoreCase(nameOfBook)){
            bookDetails = b.toString();
        }
    }
    System.out.println(bookDetails);
}

public void getBooksDataOnRange(int from, int to){
    String bookDetails = "";
    Iterator<Book> iterator = allBooks.iterator();
    while(iterator.hasNext()) {
        Book b = iterator.next();
        if(b.getIssueYear() >= from && b.getIssueYear() <= to){
            bookDetails = b.toString();
        }
    }

    if(bookDetails.isEmpty()){
        System.out.println("No books in range of: " + from + "-" + to);
    }
    System.out.println(bookDetails);
}

public void getBooksDataOnType(String type){
    String bookDetails = "";
    Iterator<Book> iterator = allBooks.iterator();
    while(iterator.hasNext()) {
        Book b = iterator.next();
        if(b.getType().equalsIgnoreCase(type)){
            bookDetails = b.toString();
        }
    }

    if(bookDetails.isEmpty()){
        System.out.println("No books of type: " + type);
    }
    System.out.println(bookDetails);
}

答案 6 :(得分:0)

如果您乐意使用第三方库,则可以使用 <Switch android:id="@+id/switch1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="8dp" android:layout_marginStart="8dp" android:layout_marginTop="152dp" android:text="Switch1" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Switch android:id="@+id/switch2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="8dp" android:layout_marginStart="8dp" android:layout_marginTop="8dp" android:text="Switch2" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/switch1" /> //////////Java Code/////////// public class MainActivity extends AppCompatActivity { Switch gSwitch,switch1, switch2; boolean state; int id; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); switch1 = findViewById(R.id.switch1); switch1 = findViewById(R.id.switch2); switch1.setOnCheckedChangeListener(checkedChangeListener); switch2.setOnCheckedChangeListener(checkedChangeListener); } CompoundButton.OnCheckedChangeListener checkedChangeListener = new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { id = buttonView.getId(); gSwitch = findViewById(id);// generic switch; state = isChecked; // call your method here for example: // BackgroundWorker backgroundWorker = new BackgroundWorker(this); // backgroundWorker.execute("switch", state, id); } }; 布尔索引。

numpy.lexsort以反向方式排序,即在numpy之前考虑A % 2

A

相关:Why NumPy instead of Python lists?

答案 7 :(得分:0)

如果你想避免使用外部库,我建议你这样做:

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

答案 8 :(得分:0)

此过程涉及在单独的临时列表中将值分为偶数和奇数,然后按升序对它们进行数字排序,最后将所有值汇总到一个列表中。下图显示了两个使用C#的项目,一个包含所有过程,而第二个更为实用,但是该过程适用于您的项目。

步骤:

  • 将原始列表一分为二,一个为偶数,另一个为几率。
  • 在“两个列表”中,按升序对它们进行排序。
  • 现在将两个列表合并到一个列表中。

Picture-1

Picture-2

Picture-3

Picture-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 = "";
                              }
    }
}

答案 9 :(得分:0)

在蟒蛇中:

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]))