【问题标题】:'for statement' without a colon [duplicate]\'for statement\' 不带冒号 [重复]
【发布时间】:2022-10-20 08:43:10
【问题描述】:
test_keys = ["Rash", "Kil", "Varsha"]
test_values = [1, 4, 5]
  
# using dictionary comprehension
# to convert lists to dictionary
res = {test_keys[i]: test_values[i] for i in range(len(test_keys))}
  
# Printing resultant dictionary 
print ("Resultant dictionary is : " +  str(res))

上面,应该有一个结束冒号“:" 在 'for 语句' 之后,例如 for i in range(3) :

但是这一行没有把“:”放在 range() 的末尾
res = {test_keys[i]: test_values[i] for i in range(len(test_keys))}
这完全不符合我所知道的语法, 这怎么可能?
也许它只是字典的语法?

【问题讨论】:

  • 冒号: 表示以下代码块引用包含该冒号的行。但是,在理解中,您不需要冒号。

标签: python syntax


【解决方案1】:

您可以使用集合、字典、列表和生成器来实现,分别称为集合、字典和列表理解或生成器表达式:

set_comprehension = {i for i in range(10)}
dict_comprehension = {i:i for i in range(10)}
list_comprehension = [i for i in range(10)]
generator_expression = (i for i in range(10))

print(set_comprehension)
print(dict_comprehension)
print(list_comprehension)
print(generator_expression)

输出:

{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
{0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9}
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
<generator object <genexpr> at 0x7fe9e8999dd0>

【讨论】:

  • 您还可以阅读reference 中的完整规范。
  • 对于生成器,它被称为生成器表达式, 不是生成器理解.
【解决方案2】:

在 python 中,: 用于表示这一行我们输入了一个新的代码块(从下一行开始的更深层次的缩进)。
前任:

if condition:
    pass #Deeper indentation
for i in range(10):
    pass #Deeper indentation
while True:
    pass #Deeper indentation
#And many others

在列表理解中,所有内容都在同一行,因此 : 不是必需的,并且会导致问题,因为下一行没有更深的缩进。

【讨论】:

    【解决方案3】:

    您所描述的称为“字典理解”,它是创建可迭代对象的另一种语法。

    它经常有用。

    类似于列表理解:

    newlist = [expression for item in iterable if condition]
    

    【讨论】:

    • 不,不是,如果它在字典中,它就是字典理解
    • 关注@Nin17。我已经养成了对两者使用相同术语的坏习惯。感谢您指出。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-24
    • 2017-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多