python中有4中不同的数据容器,那分别对应着C#中的哪种数据结构呢?
Python | Python描述 | C# |
列表list | 有序可变的,其中的每个值类型可以不一样 | List<object>,Array,HashSet<object> |
元组tuple | 有序但是值不可改变,值类型可以不一样 | List<object>,Array,HashSet<object> |
字典dict | 键值对存在,键是唯一的,键和值的类型都可以不一样 | Dictionary<object, object> |
集合set | 无序不能出现重复值,值类型可以不一样 | List<object>,Array,HashSet<object> |
1.列表
list1 = [1,"2",3]
def getlist(list2):
return list2[0]
using System;
using Microsoft.Scripting.Hosting;
using IronPython.Hosting;
using IronPython.Runtime;
class Program
{
static void Main(string[] args)
{
ScriptRuntime pyRuntime = Python.CreateRuntime();
dynamic scope = pyRuntime.UseFile("test.py");
List list = scope.list1;
List<object> list1 = list.ToList<object>();
HashSet<object> hashSet = list.ToHashSet();
Array array = list.ToArray();
object list0 = scope.getlist(new int[] { 5, 2 });
}
}
2.元组
tuple1 = (1,"2",3)
def gettuple(tuple2):
return tuple2[0]
using System;
using Microsoft.Scripting.Hosting;
using IronPython.Hosting;
using IronPython.Runtime;
class Program
{
static void Main(string[] args)
{
ScriptRuntime pyRuntime = Python.CreateRuntime();
dynamic scope = pyRuntime.UseFile("test.py");
PythonTuple pTuple = scope.tuple1;
List<object> list = pTuple.ToList();
HashSet<object> hashSet = pTuple.ToHashSet();
Array array = pTuple.ToArray();
object res = scope.gettuple(new int[] { 5, 2 });
}
}
3.字典
dict1 = {1:2,"3":4,5:"6","7":"8"}
def getdict(dict2):
return dict2["3"]
using System;
using Microsoft.Scripting.Hosting;
using IronPython.Hosting;
using IronPython.Runtime;
class Program
{
static void Main(string[] args)
{
ScriptRuntime pyRuntime = Python.CreateRuntime();
dynamic scope = pyRuntime.UseFile("test.py");
PythonDictionary pDict = scope.dict1;
Dictionary<object, object> dict = pDict.ToDictionary(k => k.Key, v => v.Value);
object res = scope.getdict(new Dictionary<object, object>() { { "3", 5 } });
}
}
4.集合
set1 = {1,2,"3",2}
def getset(set2):
return set2[0]
using System;
using Microsoft.Scripting.Hosting;
using IronPython.Hosting;
using IronPython.Runtime;
class Program
{
static void Main(string[] args)
{
ScriptRuntime pyRuntime = Python.CreateRuntime();
dynamic scope = pyRuntime.UseFile("test.py");
SetCollection pSet = scope.set1; //这里会返回3个值,因为set会去重
List<object> list = pSet.ToList();
Array array = pSet.ToArray();
HashSet<object> hashSet = pSet.ToHashSet();
object res = scope.getset(new List<object>() { "3", 5, 6, 1, "3" });
}
}