我是python中列表理解的新手。我想将for-if语句转换为list comprehension,但它没有按预期工作:
a = ['Done', 'add dns addRec test 11.11.11.11']
record = "addRec"
普通python代码:
list_new = []
for member in a:
if record and "addRec" in member:
list_new.append(member)
print(list_new)
我的清单理解:
list_new = [list_new.append(member) for member in a if record and "addRec" in member]
list_new作为空列表返回。
它应该返回:
['add dns addRec test 11.11.11.11']
答案 0 :(得分:1)
comperhension已经返回一个列表,所以我认为list_new.append(成员)是多余的。
我在没有“记录”的情况下复制了您的代码,没有附加部分。它似乎有效:
a = ['Done', 'add dns addRec test 11.11.11.11']
list_new = []
for member in a:
if "addRec" in member:
list_new.append(member)
print(list_new)
assert ['add dns addRec test 11.11.11.11'] == list_new
#comperhension
list_new = [member for member in a if "addRec" in member]
print list_new
assert ['add dns addRec test 11.11.11.11'] == list_new
编辑(在编辑问题后添加“记录”):
a = ['Done', 'add dns addRec test 11.11.11.11']
record = "addRec"
list_new = []
for member in a:
if record and "addRec" in member:
list_new.append(member)
print(list_new)
assert ['add dns addRec test 11.11.11.11'] == list_new
#comperhension
list_new = [member for member in a if record and "addRec" in member]
print list_new
assert ['add dns addRec test 11.11.11.11'] == list_new
答案 1 :(得分:1)
试试这个:
method table not found in \illuminate\Support\Faces\DB
请注意,list_new = [member for member in a if record and "addRec" in member]
函数不会返回任何内容。