在 Python 中从每行中具有不同数量组件的文件中读取数据

Reading data from file with different number of components in each line in Python

在这个项目中,我需要读取包含未知数据的输入文件并将其放入字典中。第一列始终是名称,而其余列始终是值。但是,我们不知道它可以包含多少列值。例如:

name1;1;2;3;4
name2;1;1;1
name3;5;6
name4;9

我正在考虑使用 split(';') 但每一行可能有不同的列。

for line in file:
   line = line.rstrip()
   name, value = line.split(';')
ValueError: too many values to unpack

想要的最终结果:

d={name1:[1,2,3,4], name2:[1,1,1], name3:[5,6], name4:[9]}

非常感谢您的帮助!

在这里使用 split(';') 是个好主意,这应该适合你:

filename = 'path_to_your_file'
res={}
with open(filename, 'r') as file: #opens your file in reading mode
    for line in file: #reads the file line by line
        temp = line.rstrip('\n') #removes ending newline characters
        temp = temp.split(';') #split string by ';' into a list
        res[temp.pop(0)]=temp #uses the first element of the list as dictionary key, and the rest of the list as value
print(res)

你就快完成了!拆分你的行并使用多重分配是正确的想法。缺少的部分是您可以在多重赋值中使用 * 来使一部分具有可变长度。查看 this article 了解各种用途和习语的精彩摘要。

result = {}

with open('name_of_your_file') as file:
    for line in file:
        # Set name to the first element, and set value to the rest.
        name, *value = line.rstrip().split(';')
        result[name] = value

将行读入列表后,您可以使用字典理解来执行此操作 -

正在将所有行读入列表 -

list1 = ['name1;1;2;3;4',
'name2;1;1;1',
'name3;5;6',
'name4;9']

使用字典理解 -

result_dict  ={item.split(';')[0]: item.split(';')[1:] for item in list1}
print(result_dict) 

输出-

{'name1': ['1', '2', '3', '4'],
 'name2': ['1', '1', '1'],
 'name3': ['5', '6'],
 'name4': ['9']}