Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.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 list.remove第二个列表中的项_Python_List_Python 3.x - Fatal编程技术网

Python list.remove第二个列表中的项

Python list.remove第二个列表中的项,python,list,python-3.x,Python,List,Python 3.x,我到处搜索过,我看到的大多数错误都是当人们试图迭代列表并同时修改它时出现的。在我的例子中,我尝试获取一个列表,并从该列表中删除第二个列表中的项目 import pymysql schemaOnly = ["table1", "table2", "table6", "table9"] db = pymysql.connect(my connection stuff) tables = db.cursor() tables.execute("SHOW TABLES") tablesTuple

我到处搜索过,我看到的大多数错误都是当人们试图迭代列表并同时修改它时出现的。在我的例子中,我尝试获取一个列表,并从该列表中删除第二个列表中的项目

import pymysql

schemaOnly = ["table1", "table2", "table6", "table9"]

db = pymysql.connect(my connection stuff)

tables = db.cursor()
tables.execute("SHOW TABLES")
tablesTuple = tables.fetchall()
tablesList = []

# I do this because there is no way to remove items from a tuple
# which is what I get back from tables.fetchall
for item in tablesTuple:
    tablesList.append(item)

for schemaTable in schemaOnly:
    tablesList.remove(schemaTable)
当我在代码中放入各种print语句时,一切看起来都很正常,好像都能正常工作。但是当它到达实际的
tableList.remove(schemaTable)
时,我得到了可怕的
ValueError:list.remove(x):x不在列表中

如果有更好的方法,我愿意接受。在我看来,遍历列表并删除项目是合乎逻辑的

提前谢谢

**编辑**

每个人的评论和第一个答案都是正确的。失败的原因是从元组到列表的转换正在创建一个格式非常糟糕的列表。因此,在尝试删除下一个循环中的项时,没有匹配项。这个问题的解决方案是从每个元组中提取第一个项,并将它们放入如下列表中:
tablelist=[x[0]代表tabletuple中的x]
。一旦我这样做了,第二个循环就工作了,表名被正确地删除了


谢谢你给我指明了正确的方向

我假设
fetchall
返回元组,每个匹配的数据库行对应一个元组

现在的问题是
tableList
中的元素是元组,而
schemaTable
包含字符串。Python并不认为它们是相等的。 因此,当您试图使用
schemaTable
中的字符串调用
tableList
上的
remove
时,Python找不到任何这样的值


您需要检查
表列表
中的值,并找到将它们转换为字符串的方法。我想这可能只是简单地从元组中取出第一个元素,但我手头没有mySQL数据库,因此无法测试它。

关于您的问题,如果有更好的方法,请回答:是的

您可以只附加所需的项目,而不是将项目添加到列表中,然后将其删除。例如:

for item in tablesTuple:
    if item not in schemaOnly:
        tablesList.append(item)
此外,schemaOnly可以编写为一个集合,以将搜索复杂性从O(n)提高到O(1):

这只对大列表有意义,但以我的经验,它在语义上是有用的

最后,你可以在一个列表中写下全部内容:

tablesList = [item for item in tablesTuple if item not in schemaOnly]
如果你不需要重复(或者如果一开始没有重复),你也可以这样做:

tablesSet = set(tablesTuple) - schemaOnly

在所有这些变体中,它的big-O复杂性也是最好的。

可能与
tables.fetchall()返回的元素类型重复。
?您可以通过执行
类型(表元组[0])
来实现这一点。当您执行“代码> TabelSist.Debug(Strutabase:<代码)> -StrutabyType(<代码> STR 此处)和TabLIST列表类型必须与Python相匹配时,表项中的“item”的类型可能不是Python字符串。
tablesSet = set(tablesTuple) - schemaOnly