X = [1.5, 2.3, 4.4, 5.4, 'n', 1.5, 5.1, 'a'] # Original list
# Extract non-strings from X to new listX_non_str = [el for el in X if not isinstance(el, str)] # When using only 'if', put 'for' in the beginning
# Change all strings in X to 'b', preserve everything else as isX_str_changed = ['b' if isinstance(el, str) else el for el in X] # When using 'if' and 'else', put 'for' in the end
# 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_listnumber_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))))
[expression1(item) for item in iterable]
[expression1(item) if conditional1 for item in iterable]
[expression1(item) if conditional1 else expression2(item) for item in iterable]
[expression1(item) if conditional1 else expression2(item) for item in iterable if conditional2]
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 stemmerdef best_word_feats_stem(words):return dict([(ps.stem(word), True) for word in words if word in bestwords])
# with stemmer and not stopwordsdef 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])
[item if condition else item for item in items][f(item) if condition else value for item in items][item if condition for item in items][value if condition else value1 if condition1 else value2]
age = 12s = 'minor' if age < 21 else 'adult'> minor
s的值以age值为条件。
3.带条件的列表理解
我们像这样把列表理解和条件组合在一起。
new_list = [<Conditional Expression> for <item> in <iterable>]
new_list = [<Exp1> if condition else <Exp2> if condition else <Exp3> for <item> in <iterable>]