我正在学习python这里是一个示例代码
girls = ['alice','bernice','clarice']
boys = ['chris','arnold','bob']
letterGirls = {}
for girl in girls:
letterGirls.setdefault(girl[0],[]).append(girl)
print [b+'+'+g for b in boys for g in letterGirls[b[0]]]
我收到以下错误
File "<stdin>", line 3
print [b+'+'+g for b in boys for g in letterGirls[b[0]]]
^
IndentationError: unindent does not match any outer indentation level
1)我想解决上述错误和
2)我想知道如何在 python 中的 for 循环中编写代码块,例如在上面的示例中,我在终端上检查了如果我没有在第一个 for 行下方留下空格,那么语法是错误我不清楚如何在python中的for循环代码块中给出空格是否有一些东西可以在python中留下空格
for girl in girls:
letterGirls.setdefault(girl[0],[]).append(girl)
print [b+'+'+g for b in boys for g in letterGirls[b[0]]]
根据下面的建议更新
我更新了代码打印语句在给出的示例中的 for 循环之外所以我更新了我的 ubuntu 终端上的程序
girls = ['alice','bernice','clarice']
boys = ['chris','arnold','bob']
letterGirls = {}
for girl in girls:
letterGirls.setdefault(girl[0],[]).append(girl)
print [b+'+'+g for b in boys for g in letterGirls[b[0]]]
但我仍然收到上面代码的错误
print[b+'+'+g for b in boys for g in letterGirls[b[0]]]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'c'
因为我正在终端上编写程序,这正是我的终端的样子
@ubuntu:~$ python
Python 2.7.3 (default, Aug 1 2012, 05:14:39)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> girls = ['alice','bernice','clarice']
>>> boys = ['chris','arnold','bob']
>>> letterGirls = {}
>>> for girl in girls:
... letterGirls.setdefault(girl[0],[]).append(girl)
... print [b+'+'+g for b in boys for g in letterGirls[b[0]]]
File "<stdin>", line 3
print [b+'+'+g for b in boys for g in letterGirls[b[0]]]
^
SyntaxError: invalid syntax
>>> print[b+'+'+g for b in boys for g in letterGirls[b[0]]]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'c'