在 Python 中测试 if 语句列表的优雅方式
Elegant way to test list of if statements in Python
我有一些 spreadsheets 表示为 python 中的列表列表,我正在从中生成输出。
然而,当我不得不省略 sheet 的部分时,我最终得到了一些非常难看的代码,例如:if not "string" in currentline[index] and not "string2" in currentline[index] and not
... 等等。
是否可以将所有条件表示为元组列表,比如 omit = [(0, "foo"), (5,"bar)]
,然后有一个 if 语句来检查两个语句是否为假?
如果我有这两个列表:
list = [["bar","baz","foo","bar"],["foo","bar","baz","foo","bar"]]
omit = [(0,"foo"),(4,"bar")]
我只想打印第一个,我需要一个 if 语句来测试 omit
中的每个条件,例如:
for idx, condition in enumerate(omit):
a, b = omit[idx]
if list[a] != omit[b] for all pairs of a and b in omit:
print list
您可以使用 any
和生成器表达式:
>>> seq = [["bar","baz","foo","bar"],["foo","bar","baz","foo","bar"]]
>>> omit = [(0,"foo"),(4,"bar")]
>>> for x in seq:
... if not any(i < len(x) and x[i] == v for i,v in omit):
... print(x)
...
['bar', 'baz', 'foo', 'bar']
i < len(x)
是必需的,这样我们就不会尝试访问没有元素的列表中的元素 #4。
这个版本要求omit
两个条件都不满足;如果您只想在满足两个条件时省略子列表,请将 any
替换为 all
。
对动态生成的谓词列表使用 any
和 all
。
他们每个人都接受一个可迭代的对象,并且 return 无论他们中的 any
还是 all
是否为 True —— 他们懒惰地工作。
因此,例如:
any([False, False, False]) is False
all([True, True, True]) is True
any([False, False, True]) is True
当您将它们与生成器一起使用时,美妙的部分就来了。
any(i % 2 == 0 for i in range(50)) is True
在这里,您可以将这些运算符与您的数据结构一起使用。
for row in rows:
if any(row[idx] == omittable for idx, omittable in omit):
print 'naw uh'
我有一些 spreadsheets 表示为 python 中的列表列表,我正在从中生成输出。
然而,当我不得不省略 sheet 的部分时,我最终得到了一些非常难看的代码,例如:if not "string" in currentline[index] and not "string2" in currentline[index] and not
... 等等。
是否可以将所有条件表示为元组列表,比如 omit = [(0, "foo"), (5,"bar)]
,然后有一个 if 语句来检查两个语句是否为假?
如果我有这两个列表:
list = [["bar","baz","foo","bar"],["foo","bar","baz","foo","bar"]]
omit = [(0,"foo"),(4,"bar")]
我只想打印第一个,我需要一个 if 语句来测试 omit
中的每个条件,例如:
for idx, condition in enumerate(omit):
a, b = omit[idx]
if list[a] != omit[b] for all pairs of a and b in omit:
print list
您可以使用 any
和生成器表达式:
>>> seq = [["bar","baz","foo","bar"],["foo","bar","baz","foo","bar"]]
>>> omit = [(0,"foo"),(4,"bar")]
>>> for x in seq:
... if not any(i < len(x) and x[i] == v for i,v in omit):
... print(x)
...
['bar', 'baz', 'foo', 'bar']
i < len(x)
是必需的,这样我们就不会尝试访问没有元素的列表中的元素 #4。
这个版本要求omit
两个条件都不满足;如果您只想在满足两个条件时省略子列表,请将 any
替换为 all
。
对动态生成的谓词列表使用 any
和 all
。
他们每个人都接受一个可迭代的对象,并且 return 无论他们中的 any
还是 all
是否为 True —— 他们懒惰地工作。
因此,例如:
any([False, False, False]) is False
all([True, True, True]) is True
any([False, False, True]) is True
当您将它们与生成器一起使用时,美妙的部分就来了。
any(i % 2 == 0 for i in range(50)) is True
在这里,您可以将这些运算符与您的数据结构一起使用。
for row in rows:
if any(row[idx] == omittable for idx, omittable in omit):
print 'naw uh'