• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C#调用Python(一)

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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();

 

执行结果:

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#编程中的堆栈(Stack)和队列(Queue)发布时间:2022-07-10
下一篇:
C#中[WebMethod]的用法,aspx、ashx、asmx发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap