Skip to main content
 首页 » 编程设计

python之数据从文本文件读取到python中的两个列表

2025年05月04日31bluestorm

我的文本文件格式是:

apple      very healthy 
orange     tangy and juicy 
banana     yellow in color and yummy 

我需要创建两个列表:

l1 = ['apple','orange','banana'] 
l2=['very healthy','tangy and juicy','yellow in color and yummy'] 

或将值转换成字典:

d1={'apple':'very healthy','orange':'tangy and juicy','banana':'yellow in color and yummy'} 

文件中的前两列由制表符分隔。

我尝试了以下代码将其更改为两个列表,然后将其转换为字典:

l1=[] 
l2=[] 
d={} 
read_file=open('edges.txt','r') 
split= [line.strip() for line in read_file] 
for line in split: 
    l1.append(line.split('\t')[0]) 
    l2.append(line.split('\t')[1:]) 
d=dict(zip(l1,l2)) 
print d 

我得到了一些不正确的值。我是 python 的新手..

请您参考如下方法:

确保您的文本文件包含这些值之间的制表符,我从这里复制的内容有空格。

文本文件:

apple   very healthy 
orange  tangy and juicy 
banana  yellow in color and yummy 

脚本输出:

{'orange': ['tangy and juicy'], 'apple': ['very healthy'], 'banana': ['yellow in color and yummy']}