Python 字典中的列表
我有一个这样格式的文本文件Python 字典中的列表,python,dictionary,Python,Dictionary,我有一个这样格式的文本文件 10:45 a b c x 0 1 2 y 4 5 6 z 7 8 9 我想把x作为键,把0,1,2作为它在列表中的值。和y和z一样 while(1): line = f.readline() if time in line: print (line) L1.append(line) for count,line in enumerate(f):
10:45 a b c
x 0 1 2
y 4 5 6
z 7 8 9
我想把x作为键,把0,1,2作为它在列表中的值。和y和z一样
while(1):
line = f.readline()
if time in line:
print (line)
L1.append(line)
for count,line in enumerate(f):
if (i < 3):
L1.append(line)
print ("Line{} : {}".format(count,line.strip()))
i=i+1
#print(L1)
for k in range(1):
print(L1[k])
test1 = L1[k]
a1 = test1.split()
print (a1[1])
dict = {a1[1]: L1[k] for a1[1] in L1[k]}
print (dict)
for k in range(1,3):
#print("hey")
print (L1[k]) #will list the single row
test = L1[k]
#print(test)
a = test.split()
print (a[0])
dict = {a[0]:L1[k] for a[0] in L1[k]}
print (dict)
知道我做错了什么吗?
附言-我是python新手您可以尝试以下方法:
my_dict = {}
lines = f.readLines()
lines.pop(0)
for line in lines:
line_list = line.split(' ')
key = line_list.pop(0)
my_dict.update({key: line_list})
试试这个
import string
start_found = False
result_dict = {}
for line in open("stack1_input.txt", mode='r'):
if (line.startswith("10:45")):
start_found = True
continue
if start_found == True:
values = line.split()
if len(values) == 4:
result_dict[values[0]] = values[1:]
print (result_dict)
这将实现我认为您需要的功能,假设您的文本文件存储在同一目录中,并用文件名替换“test.txt”:
with open('test.txt', 'r') as values:
contents = values.read().strip().split()
new_dict = {}
i = 4
while i <= len(contents)-4:
new_dict.update({contents[i]: contents[i+1:i+4]})
i += 4
print(new_dict)
或者,如果要将值作为整数,请执行以下操作:
with open('test.txt', 'r') as values:
contents = values.read().strip().split()
new_dict = {}
i = 4
while i <= len(contents)-4:
new_dict.update({contents[i]: [int(contents[i+1]),int(contents[i+2]),int(contents[i+3])]})
i += 4
print(new_dict)
时间的价值是什么?你面临什么问题?你得到了什么结果?