我有问题关于单行if-else语句。

huangapple go评论91阅读模式
英文:

I have problem with one-line if else statement

问题

这是一个出现的神秘问题,我这里有一个字典,尝试迭代它并创建一个新的字典:

myDict = {(i,j):(i,j,i+j) if i != j else (i,2*i,3*i,4*i) for i in range(1,7) for j in range(1,7)}

newDict = {}
for i,j in myDict.items():
    for jj in j:
        newDict[jj]=[i] if jj not in newDict.keys() else newDict[jj].append(i)

但它在第三个循环中停止,并出现以下错误:

AttributeError: 'NoneType' object has no attribute 'append'

但每当将 if else 语句更改为以下代码时:

newDict = {}
for i,j in myDict.items():
    for jj in j:
        if jj not in newDict .keys():
            newDict[jj]=[i]
        else:
            newDict[jj].append(i)

这个代码块可以正常工作,但我不知道第一个代码块的问题在哪里。

英文:

This is mystery problem that occurres, I have dictionary here and try to iterate through it and create a new dict:

myDict = {(i,j):(i,j,i+j) if i != j else (i,2*i,3*i,4*i) for i in range(1,7) for j in range(1,7)}

newDict = {}
for i,j in myDict.items():
    for jj in j:
        newDict[jj]=[i] if jj not in newDict.keys() else newDict[jj].append(i)

but it stops in third cycle and face this error:
>AttributeError: 'NoneType' object has no attribute 'append'

but when ever change the if else statement to this code:

newDict = {}
for i,j in myDict.items():
    for jj in j:
        if jj not in newDict .keys():
            newDict[jj]=[i]
        else:
            newDict[jj].append(i)

This code block works fine, but I dont know what's the problem with first code block.

答案1

得分: 5

这两段代码片段不等价,append 将返回 None,然后您尝试将这个 None 存储在 newDict[jj] 中。

您应该使用 defaultdict 代替

from collections import defaultdict
newDict = defaultdict(list)
for i, j in myDict.items():
    for jj in j:
        newDict[jj].append(i)
英文:

Those two snippets of code aren't equivalent, append will return none and then you're attempting to store that None in newDict[jj]

You should use a defaultdict instead

from collections import defaultdict
newDict = defaultdict(list)
for i,j in myDict.items():
    for jj in j:
        newDict[jj].append(i)

答案2

得分: 1

"append" 是一个原地操作,添加到列表后它不返回任何东西('None')。

错误原因解释

你在条件表达式的 if 部分进行了赋值,这意味着在后续的 else(或 elif)中,无论计算什么都将被赋值。因此,在这种情况下,else 将被计算并赋值给 newDict[jj]。

因此,当 i 的第一个迭代满足 if 条件时,它会添加到字典中。当 i 等于 2 时,else 开始起作用。因此,虽然进行了附加操作,但请记住,附加将返回 None。这就是为什么从 i=2 开始,它将 None 添加到 NewDict 的键 1、2 和 3 中的原因。一旦 None 已经存在,当第三次迭代(i=3)开始时,你无法向 None 添加任何内容,这就是你在第三个循环中出现错误的原因。
然而,如果你不使用条件表达式语法,它将正常工作。

如何更正它(如果你想坚持使用一行条件表达式)

你可以使用以下代码来确保 else 与另一种语法一起计算。请注意微小的差异。

myDict = {(i,j):(i,j,i+j) if i != j else (i,2*i,3*i,4*i) for i in range(1,7) for j in range(1,7)}

newDict = {}
for i,j in myDict.items():
    for jj in j:
        newDict[jj]=[i] if jj not in newDict.keys() else newDict[jj]+[i]
print(newDict)

打印命令给我以下结果。不确定这是否正确!这是否是你想要的?

我有问题关于单行if-else语句。

英文:

As @Sayse has already nicely pointed out that 'append' is an inplace operation and it returns nothing ('None') after adding to list.

Explanation of cause of error

You are assigning in the if condition part of the condition expression, which means that in the subsequent else (or elif) whatever is computed is going to be assigned as well. So in this case else will be computed and it will be assigned to newDict[jj].

So what is happening that for the first iteration of i your if condition is getting satisfied so it is adding to the dict. When i is equal to 2 then the else is coming into picture. So append is happening but remember append will return None. That's why it is adding None to key 1, 2 and 3 of NewDict from i=2 onwards. Once None is already there, when the iteration 3 (i=3) is starting then you can not add anything to None and that's why you are getting error in 3rd cycle.
However when you are not doing conditional expression syntax, it will work fine.

How to correct it (if you want to stick to one line conditional expression)

You can use the below code to make sure that the else is computed with alternate syntax. Please notice the subtle difference.

myDict = {(i,j):(i,j,i+j) if i != j else (i,2*i,3*i,4*i) for i in range(1,7) for j in range(1,7)}

newDict = {}
for i,j in myDict.items():
    for jj in j:
        newDict[jj]=[i] if jj not in newDict.keys() else newDict[jj]+[i]
print(newDict)

The print command gives me the following. Not sure if this is correct! Is this what you wanted?

我有问题关于单行if-else语句。

答案3

得分: 0

在你的情况下问题在于`append`返回`None`并将其写入字典。
英文:
a = 1 if False else a = 3  # wrong
a = 1 if False else 3  # correct

The problem in your case is that append returns None and writes it to the dict

huangapple
  • 本文由 发表于 2020年1月6日 18:46:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/59610701.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定