使用for循环.splitlines循环向字典添加键和值

时间:2020-01-19 21:19:43

标签: python-3.x

我试图读取一个字符串,并将第一行作为键添加到字典中,第二行作为值添加到文件末尾。 所以1代表键,2代表值,1代表键,2代表值,1代表键,2代表值... 直到文件末尾。

我正在尝试从字符串中添加键和值。 当我编写8个循环时,它工作正常,但我只想使用一个循环。 这是有效的8循环示例。

tmp_dic = {}

String = "First\nSecond\nThird\nFourth\nFifth\nSixth\nSeventh\nEight"


for x in String.splitlines()[0:1:]:
    print(x)
    x2 = x
    tmp_dic[f"{x}"] = f""
    for y in String.splitlines()[1:2:]:
        print(y)
        tmp_dic[f"{x2}"] = f"{y}"

for x in String.splitlines()[2:3:]:
    print(x)
    x2 = x
    tmp_dic[f"{x}"] = f""
    for y in String.splitlines()[3:4:]:
        print(y)
        tmp_dic[f"{x2}"] = f"{y}"

for x in String.splitlines()[4:5:]:
    print(x)
    x2 = x
    tmp_dic[f"{x}"] = f""
    for y in String.splitlines()[5:6:]:
        print(y)
        tmp_dic[f"{x2}"] = f"{y}"

for x in String.splitlines()[6:7:]:
    print(x)
    x2 = x
    tmp_dic[f"{x}"] = f""
    for y in String.splitlines()[7:8:]:
        print(y)
        tmp_dic[f"{x2}"] = f"{y}"

print(tmp_dic)

打印输出正确:

First
Second
Third
Fourth
Fifth
Sixth
Seventh
Eight

字典也很好。

{'First': 'Second', 'Third': 'Fourth', 'Fifth': 'Sixth', 'Seventh': 'Eight'}

这是一个循环的例子

tmp_dic = {}

String = "First\nSecond\nThird\nFourth\nFifth\nSixth\nSeventh\nEight"


c1 = 0
c2 = 1


for x in String.splitlines()[f"{c1}":f"{c2}":]:
    tmp_dic[f"{x}"] = f""
    c1 = c1 + 1
    c2 = c2 + 1
    for y in String.splitlines()[f"{c1}":f"{c2}":]:
        print(y)
        tmp_dic[f"{x2}"] = f"{y}"
        c1 = c1 + 1 
        c2 = c2 + 1
print(tmp_dic)

我遇到以下错误。但是c1和c2都是整数。

  File "testdic3.py", line 12, in <module>
    for x in String.splitlines()[f"{c1}":f"{c2}":]:
TypeError: slice indices must be integers or None or have an __index__ method

我也尝试过:

tmp_dic = {}

String = "First\nSecond\nThird\nFourth\nFifth\nSixth\nSeventh\nEight"


lengh = len(String.splitlines())

c1 = 0
c2 = 1

for I in range(lengh):
    x = String.splitlines()[f"{c1}":f"{c2}":]:
    tmp_dic[f"{x}"] = f""
    c1 = c1 + 1
    c2 = c2 + 1
    for y in String.splitlines()[f"{c1}":f"{c2}":]:
        print(y)
        tmp_dic[f"{x2}"] = f"{y}"
        c1 = c1 + 1
        c2 = c2 + 1

print(tmp_dic)

1 个答案:

答案 0 :(得分:1)

您的代码有奇怪的用词。 您可能想在问题中添加一个句子,以解释高级动机。

假设我们分配了lines = String.splitlines()

然后,您只需要lines[c1:c2], 而不是lines[f"{c1}":f"{c2}":]

(可以使用lines[c1:c2:], 但逐步调整大小默认为1,因此没有必要。 您可以在反转时指定它,例如lines[c2:c1:-1]。)

但是c1和c2都是整数。

真的。但是一旦您将它们变成字符串 (使用f字符串格式化程序) 那么您将无法再使用它们进行切片(或下标)。

此外,pep-8要求您将变量命名为string,而不是String。 我们将class用作初始资本,而不是使用这样的临时变量。

编辑

当您用Google搜索某物时, 您只是假设它已经存在, 然后你描述你想要的东西看起来像什么。 就像魔术一样!

在编写程序时, 您可以做出类似的假设。 您说要(键,值)对。 好吧,很公平,让我们假装有 已经提供了这些功能的功能:

def populate_dictionary():
    d = {}

    for k, v in get_pairs():
        d[k] = v

    return d

嗯,那很容易! 但是等等,现在我们必须回到困难的部分, 我们需要一个get_pairs()定义。 令人高兴的是,现在我们正在解决一个较小子问题, 容易得多:

def get_pairs(input='First\nSecond\nThird\nFourth\nFifth\nSixth\nSeventh\nEight'):
    lines = input.splitlines()
    for i in range(len(lines) // 2):
        yield lines[2 * i], lines[2 * i + 1]

Ta-da!现在我们完成了。 (当然,您可以使用像c1这样的临时变量 如果您希望避免使用花哨的2 * i表达式。) 它产生以下输出:

{'First': 'Second',
 'Third': 'Fourth',
 'Fifth': 'Sixth',
 'Seventh': 'Eight'}

(一个人可以将for循环替换为d.update(get_pairs()), 甚至更简单地通过分配d = dict(get_pairs()), 但似乎您正在使用for语句寻求练习。)