程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python 拼接C#字典格式對象

編輯:Python

依據一個Excel中的2列創建一個字典格式的數據。

例如:

將這2類字符串復制到文本中,讀取文本內容,按行讀取,每行按空格分隔。

with open(r'D:\\TestPoint.txt')as f:
for l in f:
print(l, end='')

這樣就按行讀取了數據,使用split方法風格。

with open(r'D:\\TestPoint.txt')as f:
for l in f:
temp = l.split()
print("{", '"', temp[0], '"', ',"', temp[1], '"}', ',')

輸出格式如下:

{
 " 2302 " ," A "} ,
{
 " 2303 " ," B "} ,
{
 " 2304 " ," C "} ,
{
 " 2305 " ," RLED "} ,
{
 " 2306 " ," YLED "} ,
{
 " 2307 " ," BAT "} ,
{
 " 2308 " ," TEM-1 "} ,
{
 " 2309 " ," Current "}

也使用名稱為字典的鍵,更換位置即可:

print("{", '"', temp[1], '"', ',"', temp[0], '"}', ',')

輸出:

{
 " A " ," 2302 "} ,
{
 " B " ," 2303 "} ,
{
 " C " ," 2304 "} ,
{
 " RLED " ," 2305 "}

也可以使用TestPointDataID為主鍵,自建自增變量為值

i =0
with open(r'D:\\TestPoint.txt')as f:
for l in f:
temp = l.split()
print("{" +'"' + temp\[0\] +'"' +',' +str(i), '}' +',')
i = i +1

輸出:

{
"2302",0 },
{
"2303",1 },
{
"2304",2 },
{
"2305",3 },
{
"2306",4 },
{
"2307",5 },
{
"2308",6 }

在C#中創建字典,直接將輸出的字典格式復制過去即可,依據需求可設置鍵和值的類型:

Dictionary<string, int> TestPointIndex\_Dict = new Dictionary<string, int>()
{

{
"2302",0 },
{
"2303",1 },
{
"2304",2 },
{
"2305",3 },
{
"2306",4 },
{
"2307",5 },
{
"2308",6 },
{
"2309",7 }
}

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved