python- 从输入文件创建二维字典
python- create 2-dimensional dictionary from the input file
我是 python 新手。我有一个这样的输入文件:
1 2 3 4 /a/
5 6 7 8 /b/
9 0 1 2 /c/
3 4 5 6 /d/
我需要读取文件并将数字存储在字典中,比如 d,但使用最后一列中的单词作为索引。例如我想要
d['aa'] = 1,
d['ab'] = 2,
d['ac'] = 3 ,
d['ad'] = 4
...
字典实际上不是这样工作的。字典基本上是一个散列 table。键像一组一样工作;因为不允许重复条目。我想你想做的是:
data = """1 2 3 4 /a/
5 6 7 8 /b/
9 0 1 2 /c/
3 4 5 6 /d/"""
result = {}
for line in data.split("\n"):
*numbers, index = line.split(" ")
index = index.replace("/", "")
result[index] = numbers
print(result)
字典索引未排序。如果您想保留他们的订单,您也可以随时存储:
indexes_ordered = []
...
indexes_ordered.append(index)
或查看 this question 以了解排序。
最后,要获取您的值,您可以遍历键:
for key in result:
print(result[key])
或者,根据您的选择,将 result
更改为 indexes_ordered
。您可以通过任何多种形式的列表理解对每个字典条目的有序列表进行操作。
为了加分,您可以让词典条目指向其他词典条目:
x = {}
x[0] = 1
x[1] = 2
x[2] = 3
x[3] = "yay!"
result = 0
y = 0
while y in x: y = x[y]
result = y
print(result)
要获得您在编辑后的问题中所描述的内容,您需要执行以下操作:
another_result = {}
a = ord('a')
for key in result:
x = result[key]
for n in range(len(x)):
another_result[key + chr(a+n)] = x[n]
for key in another_result: print(key, another_result[key])
如有任何问题,请发表评论。
解决方法如下:
d={};k=0;key=[];val=""
tFile=open("inputFile",'r')
dat=tFile.readlines()
for i in range(len(dat)):
val += a[i].split('/')[0] # store all the numbers in val
key.append(a[i].split('/')[1].strip()) # store letters in key
val = " ".join(val.split()) # remove extra white spaces
#merge keys and values into a single dictionary
for i in key:
for j in key:
d[i+j]=val.split(" ")[k].strip()
k+=1
return d
我是 python 新手。我有一个这样的输入文件:
1 2 3 4 /a/
5 6 7 8 /b/
9 0 1 2 /c/
3 4 5 6 /d/
我需要读取文件并将数字存储在字典中,比如 d,但使用最后一列中的单词作为索引。例如我想要
d['aa'] = 1,
d['ab'] = 2,
d['ac'] = 3 ,
d['ad'] = 4
...
字典实际上不是这样工作的。字典基本上是一个散列 table。键像一组一样工作;因为不允许重复条目。我想你想做的是:
data = """1 2 3 4 /a/
5 6 7 8 /b/
9 0 1 2 /c/
3 4 5 6 /d/"""
result = {}
for line in data.split("\n"):
*numbers, index = line.split(" ")
index = index.replace("/", "")
result[index] = numbers
print(result)
字典索引未排序。如果您想保留他们的订单,您也可以随时存储:
indexes_ordered = []
...
indexes_ordered.append(index)
或查看 this question 以了解排序。
最后,要获取您的值,您可以遍历键:
for key in result:
print(result[key])
或者,根据您的选择,将 result
更改为 indexes_ordered
。您可以通过任何多种形式的列表理解对每个字典条目的有序列表进行操作。
为了加分,您可以让词典条目指向其他词典条目:
x = {}
x[0] = 1
x[1] = 2
x[2] = 3
x[3] = "yay!"
result = 0
y = 0
while y in x: y = x[y]
result = y
print(result)
要获得您在编辑后的问题中所描述的内容,您需要执行以下操作:
another_result = {}
a = ord('a')
for key in result:
x = result[key]
for n in range(len(x)):
another_result[key + chr(a+n)] = x[n]
for key in another_result: print(key, another_result[key])
如有任何问题,请发表评论。
解决方法如下:
d={};k=0;key=[];val=""
tFile=open("inputFile",'r')
dat=tFile.readlines()
for i in range(len(dat)):
val += a[i].split('/')[0] # store all the numbers in val
key.append(a[i].split('/')[1].strip()) # store letters in key
val = " ".join(val.split()) # remove extra white spaces
#merge keys and values into a single dictionary
for i in key:
for j in key:
d[i+j]=val.split(" ")[k].strip()
k+=1
return d