'小甲鱼''小客服'那一课的赋值问题
a = open('d:/record.txt')b = []
g = []
count = 1
for each_line in a :
if each_line[:6] != '======':
(role,each_spoken) = each_line.split(':',1)
if role == '小甲鱼':
boy_spoken = b.append(each_spoken)
if role == '小客服':
girl_spoken = g.append(each_spoken)
else :
boy_file_name = 'boy_' + str(count) + '.txt'
girl_file_name = 'girl_' + str(count) + '.txt'
boy_file = open(boy_file_name,'w')
girl_file = open(girl_file_name,'w')
boy_file.writelines(boy_spoken)
girl_file.writelines(girl_spoken)
boy_file.close()
girl_file.close()
b =[]
g = []
count += 1
上面是我自己看完视频后复习的时候重新打的代码,基本一样,但是运行出错,提示如下:
Traceback (most recent call last):
File "D:/Python/review.py", line 19, in <module>
boy_file.writelines(boy_spoken)
TypeError: 'NoneType' object is not iterable
我发现可能是'boy_spoken'好像不是变量,所以不能写入.
我看了下课件:对如下:
原程序:
for each_line in a :
if each_line[:6] != '======':
(role,each_spoken) = each_line.split(':',1)
if role == '小甲鱼':
boy.append(each_spoken)
if role == '小客服':
girl.append(each_spoken)
出错程序:
for each_line in a :
if each_line[:6] != '======':
(role,each_spoken) = each_line.split(':',1)
if role == '小甲鱼':
boy_spoken = b.append(each_spoken)
if role == '小客服':
girl_spoken = g.append(each_spoken)
好像也就是多了一步赋值,怎么就没用了?难道是全局变量跟局部变量的问题?但是我看了下程序流程,按道理'boy_spoken'也应该能在下面生效的啊,如果没定义的话,出错的提示应该是'is not defined'吧? boy.append(each_spoken)是没有返回值的,在python中会默认返回NONE,也就是说你的boy_spoken = NONE,所以报错了 枫还 发表于 2019-2-8 12:53
boy.append(each_spoken)是没有返回值的,在python中会默认返回NONE,也就是说你的boy_spoken = NONE,所以 ...
这个返回值的概念是怎么理解呢?
我append了以后, boy的列表实际是已经增加了内容,如下,
>>> boy_spoken
>>> b
['小甲鱼:咦??\n', '小甲鱼:。。。。。。\n', '小甲鱼:然后呢?\n', '小甲鱼:呃。。。。。。你真牛!\n', '小甲鱼:下次有人想调戏你我不阻止~\n', '小甲鱼:哦?\n', '小甲鱼:哈哈哈,我看到丫,我还发微博了呢~\n', '小甲鱼:哟西~\n', '小甲鱼:T_T\n', '小甲鱼:哦?什么事?\n', '小甲鱼:哪里的?\n', '小甲鱼:那正常,哪家公司?\n', '小甲鱼:哦\n', '小甲鱼:啊,你说什么?我在外边呢,这里好吵吖。。。。。。\n']
不是说Pyhon只有名字,没有变量么,那么我之前 boy_spoken = boy 的这个操作,不是应该吧 b 列表的内容指向了boy_spoken么,
还有,如果我之前的操作是废操作,那么如果我希望用一个变量名指向那个boy.append(each_spoken),那么应该怎么操作呢? boy.append(each_spoken)是调用append方法将each_spoken加入boy里面,它是python要去做的一个动作,你想做的应该是把boy_spoken指向b的内容吧,boy_spoken = b.append(each_spoken)并不能做到这样的事情,因为赋值号右边并不是b,直接boy_spoken = b 就行了 非ettype”对象不可迭代(百度对 'NoneType' object is not iterable的翻译) 看来还有很多东西要学习啊!
页:
[1]