从文本文件创建编号列表

2024-04-16 09:19:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望将文本文件中的名称列表转换为字典,名称前面的数字作为列表

文本文件:

Adam A
Bob B
Charles C

文本文件每行只有一个名称

预期结果:

{1: 'Adam A', 2: 'Bob B', 3: 'Charles C'}

到目前为止,这是我当前的代码

numbered_dict = {}
namelist = open("data.txt")
for line in namelist:
    a=0
    a+=1
    numbered_dict[a]=line

输出为:

{1: 'Charles C'}

出于某种原因,它只取名单上的最后一个名字

任何帮助都将不胜感激,谢谢


Tags: 代码名称列表data字典line数字open
3条回答

您应该在循环上方而不是内部初始化a=0。你的代码应该是

numbered_dict = {}
namelist = open("data.txt")
a=0
for line in namelist:
    a+=1
    numbered_dict[a]=line
for line in namelist:
    a=0
    a+=1
    numbered_dict[a]=line

每次通过循环都将a设置为0,然后将其增加为1

必须在循环外部初始化变量:

a=0
for line in namelist:
    a+=1
    numbered_dict[a]=line

但是,作为更好的工具,您可以使用dict构造函数和enumerate函数:

numbered_dict = dict(enumerate(open("data.txt")))

试试这个:

import csv
# Create a dictionary that will contain the file data
dic = {}
# Open the file and read it
with open('data.txt', 'r') as fd:
    # contain file in a list
    reader = csv.reader(fd)
    # Create a counter that will be the key of a line in the file
    count = 1
    for row in reader:
        dic[count] = row[0]
        count += 1
print(dic)

相关问题 更多 >