Warm tip: This article is reproduced from serverfault.com, please click

python-不带冒号的“for 语句”

(python - 'for statement' without a colon)

发布于 2022-04-27 12:14:54
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 语句”之后,就像 i(3) 中的 i 一样

但是这一行没有在 range()

的末尾加上“:”,这完全超出了我知道的语法,这怎么可能?
也许是仅用于字典的语法?
res = {test_keys[i]: test_values[i] for i in range(len(test_keys))}

Questioner
bbiot426
Viewed
0
Nin17 2022-04-27 20:32:07

你可以使用集合,字典,列表和生成器来做到这一点,并分别称为集合,字典和列表推导或生成器表达式:

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>