依據一個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 }
}