如何将一个列表从文件转换成字典

2024-09-29 23:18:44 发布

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

我有一个文件我想在循环中运行。我的文件如下所示:

Hello Hello
A B C D
A B C D
B C D A
B C D A
C D A B
B C D A

Hello Bye
A C D B
C D A B
A C D B
D C A B

我只在“再见”和“空行”之间循环。你知道吗

它应该返回:

 {(A, C, D, B): 2, (C, D, A, b):1, (D, C, A, B):1}

有没有一种方法我可以称之为“all”来添加所有的排列?你知道吗

我不想使用任何导入。你知道吗

到目前为止,我的函数如下所示:

# input_word = Hello or Bye
def file_to_dict (file, input_word):
    new_dict = {}
    new_list = []

    flag = False
    for line in f:
        if 'Hello' in line:
            continue
        if not line.strip():
            continue
        lElts = tuple(line.split(' '))
        if lElts in dRet:
            dRet[lElts] += 1
        else:
            dRet[lElts] = 1
    return dRet

有没有其他选择继续?你知道吗

这给了我一个错误:

ValueError: I/O operation on closed file

Tags: 文件inhellonewinputiflinedict
3条回答

类似于这样,在hello Bye处拆分,然后使用dict.get()向字典添加值。你知道吗

In [17]: with open("data.txt") as f:

    spl=f.read().split("Hello Bye")

    #now spl[1] is  

    #
    #A C D B
    #C D A B
    #A C D B
    #D C A B

    #we need to now split these at '\n', or may be use `splitlines()`
    #for every line apply split, which returns ['D', 'C', 'A', 'B']
    #apply tuple() to it, to make it hashable.
    #now you can use use either defaultdict(int) or dict.get() as used below.

    dic={}                         
    for x in spl[1].split('\n'):
        if x.strip():
            key=tuple(x.split())
            dic[key]=dic.get(key,0)+1;
    print dic
   ....:     
{('D', 'C', 'A', 'B'): 1, ('A', 'C', 'D', 'B'): 2, ('C', 'D', 'A', 'B'): 1}
read = False    
counting_dict = {}
#run through the lines in the file
for line in file:
    if read and 'Hello' not in line:
        #do as if the entry already exists
        try:
            counting_dict[tuple(line.split())] += 1
        #if not, create it
        except KeyError:
            counting_dict[tuple(line.split())] = 1
    elif 'Bye' in line:
        read = True
    #if 'Hello' is in the line but 'Bye' is not,set read to False
    else:
        read = False

有很多逻辑错误。。。我建议你查一下elif的工作原理

def f_to_dict(f):
    dRet = {}
    for line in f:
        if 'Hello' in line:
            continue
        if not line.strip():
            continue
        lElts = tuple(line.split(' '))
        if lElts in dRet:
            dRet[lElts] += 1
        else:
            dRet[lElts] = 1
    return dRet

相关问题 更多 >

    热门问题