我有一个包含字符串和None值的列表xs。如何使用列表理解来调用每个字符串上的函数,但将None值转换为“”(而不是将它们传递给函数)?
我尝试了:
[f(x) for x in xs if x is not None else '']
但它给出了SyntaxError。正确的语法是什么?
如果您试图创建一个省略基于条件的值的列表理解,请参阅带条件的列表理解。
如果需要考虑两个以上的条件结果,请注意Python的条件表达式不支持elif。相反,需要嵌套if/else条件。有关详细信息,请参见列表理解条件中的“elif”。
下面是另一个示例:
>>> print(", ".join(["ha" if i else "Ha" for i in range(3)]) + "!")
Ha, ha, ha!
它利用了这样一个事实,即如果我对0求值为False,对函数range()生成的所有其他值求值为True。因此,列表理解评估如下:
>>> ["ha" if i else "Ha" for i in range(3)]
['Ha', 'ha', 'ha']
# coding=utf-8
def my_function_get_list():
my_list = [0, 1, 2, 3, 4, 5]
# You may use map() to convert each item in the list to a string,
# and then join them to print my_list
print("Affichage de my_list [{0}]".format(', '.join(map(str, my_list))))
return my_list
my_result_list = [
(
number_in_my_list + 4, # Condition is False : append number_in_my_list + 4 in my_result_list
number_in_my_list * 2 # Condition is True : append number_in_my_list * 2 in my_result_list
)
[number_in_my_list % 2 == 0] # [Condition] If the number in my list is even
for number_in_my_list in my_function_get_list() # For each number in my list
]
print("Affichage de my_result_list [{0}]".format(', '.join(map(str, my_result_list))))
(venv)$python list_comp.py我的联系列表[0,1,2,3,4,5]我的联系结果列表[0,5,4,7,8,9]
因此,对于您:row=[(“”,unicode(x.strip()))[x不是None](对于行中的x)]
你可以在理解中结合条件逻辑:
ps = PorterStemmer()
stop_words_english = stopwords.words('english')
best = sorted(word_scores.items(), key=lambda x: x[1], reverse=True)[:10000]
bestwords = set([w for w, s in best])
def best_word_feats(words):
return dict([(word, True) for word in words if word in bestwords])
# with stemmer
def best_word_feats_stem(words):
return dict([(ps.stem(word), True) for word in words if word in bestwords])
# with stemmer and not stopwords
def best_word_feats_stem_stop(words):
return dict([(ps.stem(word), True) for word in words if word in bestwords and word not in stop_words_english])