Python 3.1.1 Problem With Tuples
This piece of code is supposed to go through a list and preform some formatting to the items, such as removing quotations, and then saving it to another list.
class process:
def rchr(string_i, asciivalue):
string_o = ()
for i in range(len(string_i)):
if ord(string_i[i]) != asciivalue:
string_o += string_i[i]
return string_o
def flist(self, list_i):
cache = ()
cache_list = []
index = 0
for line in list_i:
cache = line.split('\t')
cache[0] = process.rchr(str(cache[0]), 34)
cache_list.append(cache[0])
cache_list[index] = cache
index += 1
cache_list.sort()
return cache_list
p = process()
list1a = ['cow', 'dog', 'sheep']
list1 = p.flist(list1a)
print (list1)
However; it chokes at string_o += string_i[i]
and gives the following error:
Traceback (most recent call last):
File "/Projects/Python/safafa.py", line 23, in <module>
list1 = p.flist(list1a)
File "/Projects/Python/safafa.py", line 14, in flist
cacbe[0] = process.rchr(str(cache[0]), 34)
File "/Projects/Python/safafa.py", line开发者_如何学Python 7, in rchr
string_o += string_i[i]
TypeError: can only concatenate tuple (not "str") to tuple
I think you want string_o = ""
instead of string_o = ()
Your problem is that you want string_o
to be a string so you can append other strings onto it. Setting it equal to ()
makes it a tuple instead, which is a data type incompatible with string.
In addition to the previous answer, a more pythonic way to go would be:
string_o = ''.join(c for c in string_i if ord(c) != asciivalue)
It is short and readable.
To add to Olivier's answer, I think the whole code could be replaced with:
import itertools
output = [i.replace('"','') for i in list(itertools.chain(*(x.split('\t') for x in input)))]
Tested with python 2.x only.
精彩评论