C#調用Python(一)


python文件中未引入其他包、模塊

以下方法不適用於pyhton 文件有第三方包、模塊,有第三方包,模塊的實現方法,請戳這里→https://www.cnblogs.com/zhuanjiao/p/12007176.html

一、安裝IronPython包,使用的是2.7.5版本

 

 二、源碼

 2.1 python 源碼,實現一個快速排序功能

def quickSort(lyst):
    quickSortHelper(lyst, 0, len(lyst) - 1)
    return lyst


def quickSortHelper(lyst, left, right):
    if left < right:
        pivotLocation = partition(lyst, left, right)
        quickSortHelper(lyst, left, pivotLocation - 1)
        quickSortHelper(lyst, pivotLocation + 1, right)

def swap(lst, i, j):
    temp = lst[i]
    lst[i] = lst[j]
    lst[j] = temp


def partition(lyst, left, right):
    middle = (left + right) // 2
    pivot = lyst[middle]
    lyst[middle] = lyst[right]
    lyst[right] = pivot
    boundary = left
    for index in range(left, right):
        if lyst[index] < pivot:
            swap(lyst, index, boundary)
            boundary += 1
    swap(lyst, right, boundary)
    return boundary

  2.2 C#源碼

using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

namespace TestClass
{
    public class CSharpCallPython
    {
        public int[] Sort(int[] arr)
        {
            string path = @"D:\PyCharm\source\Study\test.py";
            ScriptRuntime pyRuntime = Python.CreateRuntime();
            dynamic py = pyRuntime.UseFile(path);
            return py.quickSort(arr);
        }
    }
}
var arr = new CSharpCallPython().Sort(new int[] { 45, 12, 87, 2, 204, 3 });
            foreach (var item in arr)
            {
                Console.WriteLine(item);
            }
            Console.ReadLine();

 

執行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM