Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么Python在尝试调用读取文本的函数时给出TypeError?_Python_Python 3.x - Fatal编程技术网

为什么Python在尝试调用读取文本的函数时给出TypeError?

为什么Python在尝试调用读取文本的函数时给出TypeError?,python,python-3.x,Python,Python 3.x,所以我有一个代码来给出一个字符在文本文件中的位置,使用的函数代码如下所示 #this is defined function def return_position(arr, search_for=[''], base=1): dim = () arr = [str(arr) for arr in arr] for search in search_for: for sr in range(len(arr)): s = arr[sr

所以我有一个代码来给出一个字符在文本文件中的位置,使用的函数代码如下所示

#this is defined function
def return_position(arr, search_for=[''], base=1):
    dim = ()
    arr = [str(arr) for arr in arr]
    for search in search_for:
        for sr in range(len(arr)):
            s = arr[sr]
            for cr in range(len(s)):
                c = s[cr]
                if c == search:
                    dim += [(cr+base, sr+base)]
    return dim
为了获得文件列表,我使用了
.readlines()
,因为它包含一个列表,并且将得到预期的结果,所以我这样做了

#open the file and read it as a list
textlist = open('testfile.text', 'r').readlines()
#textlist = ['Build a machine\n', 'For the next generation']

#print the return_position as a lines
print(''.join(return_position(textlist, search_for=['a', 'b'])))
testfile.txt中

Build a machine
For the next generation
预期结果

(1, 1)
(7, 1)
(10, 1)
(19, 2)
但是为什么它会回来呢

TypeError只能将元组(而不是“列表”)连接到元组

如果
dim
是一个元组,则此行不起作用

转这个

dim = ()
进入

元组是一个不可变的有序序列。你不能在上面附加东西。因此,请使用列表


Ref:

在您的代码中
dim
是一个
元组
,元组是不可变的(即,在构建之后不能修改)

您需要将
dim
转换为
列表
,以便能够附加到其中:

dim = []

正如其他答案所指出的,元组是不可变的,不能更改。 然而,这并不能回答您的问题,因为您并没有试图更改元组,而是试图连接元组和列表。Python不知道您是想要一个元组还是一个列表,因此它会引发TypeError

将两个元组串联在一起工作:

(1,2) + (3,4)  # result: (1, 2, 3, 4)
连接两个列表也可以:

[1,2] + [3,4]  # result: [1, 2, 3, 4]
只有元组和列表的混合会导致问题:

[1,2] + (3,4)  # raises TypeError
因此(正如其他答案已经指出的)更改任一操作数的数据类型可以解决问题

出于效率原因,我建议使用列表并附加到其中,而不是串联:

def return_position(arr, search_for=[''], base=1):
    dim = []  # changed this line
    arr = [str(arr) for arr in arr]
    for search in search_for:
        for sr in range(len(arr)):
            s = arr[sr]
            for cr in range(len(s)):
                c = s[cr]
                if c == search:
                    dim.append((cr+base, sr+base))  # changed this line
    return dim

textlist = ['Build a machine\n', 'For the next generation']

#print the return_position as a line
print(''.join(str(return_position(textlist, search_for=['a', 'b']))))  # added explicit conversion to str
您的打印也引发了一个类型错误,因为传递给
str.join
的iterable的所有元素都必须是字符串。它不像
print
功能那样执行显式转换


编辑: 请注意,尽管该算法不再引发错误,但由于该算法区分大小写,因此缺少一个预期结果。 如果希望它不区分大小写,请使用
str.casefold
str.lower
,请参阅。
我不会使用
casefold
来确保一个“ß”不会被一个“ss”替换,可能会将这个词变成一个不同的单词,具有不同的发音和不同的含义,就像链接答案中的示例一样(例如,“busse”不应等于“buße”)。

这与您的问题无关,但是考虑在 ARR=(ARR中的ARR)的STR(ARR)中给出循环变量:一个与您正在迭代的事物不同的名称。NPE你是什么意思?在这一行代码中有三个不同的东西叫做
arr
(1)你正在迭代的东西;(2) 循环变量;(3) 列表理解结果的名称。(1)+(3)有相同的名字是可以的(习惯上是偶数)。最好给(2)一个不同的名称,例如,
arr=[str(val)for val in arr]
。如果您只是想找到字符串的位置,可以用一个for loop和do.index()遍历行以获得位置。另外,作为一项建议,请尝试使用适当的变量名使代码可读。@badc0re否否,如果使用object.index(x),它将只返回一个值,这不是我想要的
[1,2] + (3,4)  # raises TypeError
def return_position(arr, search_for=[''], base=1):
    dim = []  # changed this line
    arr = [str(arr) for arr in arr]
    for search in search_for:
        for sr in range(len(arr)):
            s = arr[sr]
            for cr in range(len(s)):
                c = s[cr]
                if c == search:
                    dim.append((cr+base, sr+base))  # changed this line
    return dim

textlist = ['Build a machine\n', 'For the next generation']

#print the return_position as a line
print(''.join(str(return_position(textlist, search_for=['a', 'b']))))  # added explicit conversion to str