循环在字典中

时间:2016-02-29 17:43:50

标签: python dictionary

我正在制作拉丁方板拼图,我正在制作代码以打开文本文件并将数据存储在字典中。然而,当我遍历代码时,它会重复打印出来。 例如,在我的文本文档中,我有

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:]

但我不确定如何解决这个问题

4 个答案:

答案 0 :(得分:0)

将您的电路板存储在二维列表中更有意义:

with open(filename, 'r') as f:
    board = [list(line) for line in f.read().splitlines()]

for row in board:
    print(row)

输出:

['A', 'B', 'C']
['C', 'A', 'B']
['B', 'C', 'A']

然后可以根据其坐标选择一个值:

board[0][0] # top left 'A'
board[2][2] # bottom right 'A'

答案 1 :(得分:0)

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

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循环将其打印出来,就像在

中读取它一样

答案 2 :(得分:0)

指出问题是正确的。

您需要清空变量:

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")

答案 3 :(得分:0)

首先,您应该将其存储为列表(或列表列表),而不是将其作为字典。

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