循环输入字典

2024-04-16 06:39:41 发布

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

我正在做一个拉丁方块拼图,我正在做代码来打开一个文本文件并将数据存储在字典中。但是,当我循环代码时,它会重复打印出来。 例如在我的文本文档中

ABC
CAB
BCA

当我运行代码时,我希望输出是我得到的

ABC
ABCCAB
ABCCABBCA 

我现在的代码是:

d={}
while True:
    try:
        filename=input("Enter the name of the file to open: ") + ".txt"
        with open(filename,"r") as f:
            for line in f:
                splitLine=line.split()
                d[splitLine[0]]=splitLine[1:]
                #print(line, end="")
                print(d)
            break

    except FileNotFoundError:
        print("File name does not exist; please try again")

我到底需要怎么做才能停止打印上面的行。我认为这与:

d[splitLine[0]]=splitLine[1:]

但我不知道如何解决这个问题


Tags: the数据代码name字典line文本文档open
3条回答

首先,你应该把它存储为一个列表(或者列表列表),而不是把它变成一个字典。你知道吗

d=[]
while True:
    try:
        #filename=input("Enter the name of the file to open: ") + ".txt"
        with open("file.txt","r") as f:
            for line in f:
                splitLine=line.split()
                d.extend(splitLine)
                #print(line, end="")

            break

    except FileNotFoundError:
        print("File name does not exist; please try again")

for elem in d:
        print elem 

如果您使用这样的列表结构,然后最后使用循环遍历所有元素,您将获得所需的输出。你知道吗

输出:

ABC
CAB
BCA

你指出问题是对的。你知道吗

您需要清空变量:

d

每次你循环。你知道吗

示例:

d={}
while True:
    try:
        filename=input("Enter the name of the file to open: ") + ".txt"
        with open(filename,"r") as f:
            for line in f:
                splitLine=line.split()
                d[splitLine[0]]=splitLine[1:]
                print(line, end="")
                d={}
            break

    except FileNotFoundError:
        print("File name does not exist; please try again")

正如其他人所指出的,列表可能是一个更好的选择,为您的游戏板。你可以这样做:

d = []
while True:
    try:
        filename = 'foo.txt'
        with open(filename, "r") as f:
            for line in f:
                d.append(list(line.strip()))
            break

    except FileNotFoundError:
        print("File name does not exist; please try again")

print(d)

for line in d:
    print(''.join(line))

这将输出:

[['A', 'B', 'C'], ['C', 'A', 'B'], ['B', 'C', 'A']]
ABC
CAB
BCA

for循环会像你读的那样打印出来

相关问题 更多 >