我希望我的问题有道理。如果IF
语句证明是正确但我收到错误,我希望加入最后2个索引。
这是我的文本文件:
AAA BBB CCC NY 10018 111111111E
AAA BBB CCC DDD NY 11946222222222E
AAA BBB CCC NY 10018 333333333E
AAA BBB CCC DDD NY 11946444444444E
这是我的代码:
with open('O:/python1docs/sample_1.txt', 'rb') as infile:
data1 = []
for row in infile:
row = row.strip().split()
rend = len(row) - 1
rend2 = rend - 1
rend3 = rend2 - 1
if len(row[rend]) == 10 and len(row[rend2]) == 5 and len(row[rend3]) == 2:
row = row[0:rend2] + ' ' + ''.join(row[rend2] + row[rend])
data1.append(row)
else:
data1.append(' '.join(row))
print '\n'.join(data1)
我收到错误消息:
Traceback (most recent call last):
File "O:\python1\py_programs\lipa_newbiz3.py", line 12, in <module>
row = row[0:rend2] + ' ' + ''.join(row[rend2] + row[rend])
TypeError: can only concatenate list (not "str") to list
[Finished in 0.2s with exit code 1]
我可以加入任何单个索引,即:row = row[*] + ' ' + ''.join(row[rend2] + row[rend])
并且代码有效,但是当我尝试将所有索引加在一起row[0:rend2] + ' ' + ''.join(row[rend2] + row[rend])
时,它会出错
非常感谢任何帮助。 -Thanks
这就是我想要的
['AAA BBB CCC NY 10018111111111E']
['AAA BBB CCC DDD NY 11946222222222E']
['AAA BBB CCC NY 10018333333333E']
['AAA BBB CCC DDD NY 11946444444444E']
更长的方式
for row in infile:
row = row.strip().split()
rend = len(row) - 1
rend2 = rend - 1
rend3 = rend2 - 1
row1 = []
templist1 = []
templist2 = []
templist3 = []
templist4 = []
templist5 = []
if len(row[rend]) == 10 and len(row[rend2]) == 5 and len(row[rend3]) == 2:
templist1.append(' '.join(row[0:rend2]))
templist2.append(row[rend2])
templist3.append(row[rend])
templist4.append(' '.join(templist1 + templist2))
templist5.append(''.join(templist4 + templist3))
print ' '.join(templist5)
else:
row = ' '.join(row)
print row
这是一个更短的方式
for row in infile:
row = row.strip().split()
rend = len(row) - 1
rend2 = rend - 1
rend3 = rend2 - 1
if len(row[rend]) == 10 and len(row[rend2]) == 5 and len(row[rend3]) == 2:
row = ' '.join(row[0:rend2]) + ' ' + ''.join(row[rend2] + row[rend])
print row
else:
row = ' '.join(row)
print row
答案 0 :(得分:1)
您不能将'+'运算符应用于字符串和列表类型
row = ' '.join(row[0:rend2]) + ' ' + ''.join(row[rend2] + row[rend])
或
tmplist = row[0:rend2]
row = ' '.join(tmplist.append(''.join(row[rend2] + row[rend])))