在pyqt中我有一个qtableview,用户可以编辑。如果用户对表进行了更改,则在用户完成时将复制该表。如果未进行任何更改,则跳过该表。该表填充空字符串,即:
table = [["","",""],["","",""]]
我想检查表中是否只包含""
,如果只包含"1"
,请忽略它。如果它没有,即包含tabell1 = [["","",""],["","",""]]
meh = 0
for item in self.tabell1:
for item1 in item:
if item1 == "":
pass
else:
meh = 1
if meh == 1:
do the thing
,则列表上会运行一些代码。
现在我有一个工作代码,但它不是非常pythonic,我想知道如何改进它。我的代码如下:
routes.MapRoute(
"sitemap",
"sitemap.xml",
New With {.controller = "XmlSiteMap", .action = "Index"}
)
答案 0 :(得分:1)
要检查任何子列表中的任何元素是否满足条件,您可以使用any
和嵌套的生成器表达式:
tabell1 = [["","",""],["","",""]]
if any(item for sublist in tabell1 for item in sublist):
# do the thing
这也有一个好处,就是一旦找到一个非空字符串就会停止!您的方法将继续搜索,直到它检查了所有子列表中的所有项目。
空字符串被视为False
,并且包含至少一个项目的每个字符串都被视为True
。但是,您也可以明确地与空字符串进行比较:
tabell1 = [["","",""],["","",""]]
if any(item != "" for sublist in tabell1 for item in sublist):
# do the thing
答案 1 :(得分:0)
我看到的主要事情可能是更加pythonic是使用空字符串被认为是假的事实,像这样...
tabell1 = [["","",""],["","",""]]
meh = 0
for sublist in self.tabell1:
if any(sublist): # true if any element of sublist is not empty
meh = 1
break # no need to keep checking, since we found something
if meh == 1:
do the thing
答案 2 :(得分:0)
或者你可以通过将列表转换为字符串来避免循环遍历列表,删除仅在它为空时出现的所有字符,然后检查它是否为空:
tabell1 = [["","",""],["","",""]]
if not str(tabell1).translate(None, "[]\"\', "):
#do the thing
虽然这意味着只包含[
,]
,"
,'
和实例的任何表都将被视为空。< / p>