在文件中获取格式化列表以列出python

2024-04-26 06:10:48 发布

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

我有一个与另一封信对应的信件列表的文件:

A['B', 'D']
B['A', 'E']
C[]
D['A', 'G']
E['B', 'H']
F[]
G['D']
H['E']

我需要将这些列表导入到它们相应的字母中,希望有这样的变量:

vertexA = ['B', 'D']
vertexB = ['A', 'E']
vertexC = []
vertexD = ['A', 'G']
vertexE = ['B', 'H']
vertexF = []
vertexG = ['D']
vertexH = ['E']

最好的办法是什么?我试着寻找答案,但运气不好。谢谢你的帮助。你知道吗


Tags: 文件答案列表字母信件办法运气vertexe
3条回答

读取输入文件时,输入应如下所示:

string='A["B","C"]'

所以,我们知道第一个字母是名单的名字。你知道吗

import ast
your_list=ast.literal_eval(string[1:])

your_list:
['B', 'C']

您可以处理循环、读取文件和字符串操作以获得正确的命名。。。你知道吗

你可以尝试使用字典而不是变量,我认为这也使得从文本文件填充数据变得更容易。你知道吗

vertex = {}
vertex['A'] = ['B', 'D']
vertex['A']
>>> ['B', 'D']

最好是编一本字典。字母表中的每个字母都将是一个键,然后值将是相关字母的列表。以下是概念证明(未经测试):

from string import string.ascii_uppercase

vertices = {}

# instantiate dict with uppercase letters of alphabet
for c in ascii_uppercase:
    vertices[c] = []

# iterate over file and populate dict
with open("out.txt", "rb") as f:
    for i, line in enumerate(f):
        if line[0].upper() not in ascii_uppercase:
            # you probably want to do some additional error checking
            print("Error on line {}: {}".format(i, line))
        else:  # valid uppercase letter at beginning of line
            list_open = line.index('[')
            list_close = line.rindex(']') + 1  # one past end
            # probably would want to validate record is in correct format before getting here
            # translate hack to remove unwanted chars
            row_values = line[list_open:list_close].translate(None, "[] '").split(',')
            # do some validation for cases where row_values is empty
            vertices[line[0].upper()].extend([e for e in row_values if e.strip() != ''])

使用它会很容易:

for v in vertices['B']:
    # do something with v

相关问题 更多 >