转自:[https://www.cnblogs.com/bigtreei/p/14207944.html](https://www.cnblogs.com/bigtreei/p/14207944.html) # 1. Outline 平时写if判断和for循环都是中规中矩,按常规套路来,但今天同事问我这方面的东西给; 把他for循环+if else判断改成了一行。 改完之后代码看起来更**优雅**了 哈哈哈 # 2. 需求 假设有这么个需求: 判断一个可迭代对象中的元素是否以字母 “s” 结尾; 1. 以 “s” 结尾,则保留这个元素 2. 不以 “s” 结尾,则把这个元素替换为 666 # 3. 实现 首先要for循环遍历这个可迭代对象,然后对每次迭代的元素进行判断,看是否以“s”结尾; 常规解法: ```python def is_endwith_s(n): """ 判断是否以s结尾 :param n: str or int :return: bool """ return str(n).endswith('s') # 待判断的可迭代对象 lis = ['ss', 'ss', 'ss', 'aa', 'aa', 'ss', 'ss', 'ss', 'ss', '22'] lis_s = [] for i in lis: if is_endwith_s(i): lis_s.append(i) print(lis_s) # ['ss', 'ss', 'ss', 'ss', 'ss', 'ss', 'ss'] ``` ```python def is_endwith_s(n): """ 判断是否以s结尾 :param n: str or int :return: bool """ return str(n).endswith('s') # 待判断的可迭代对象 lis = ['ss', 'ss', 'ss', 'aa', 'aa', 'ss', 'ss', 'ss', 'ss', '22'] lis_s = [] for i in lis: if is_endwith_s(i): lis_s.append(i) else: lis_s.append(666) print(lis_s) # ['ss', 'ss', 'ss', 666, 666, 'ss', 'ss', 'ss', 'ss', 666] ``` for循环+ if else 一行实现: ```python def is_endwith_s(n): """ 判断是否以s结尾 :param n: str or int :return: bool """ return str(n).endswith('s') # 待判断的可迭代对象 lis = ['ss', 'ss', 'ss', 'aa', 'aa', 'ss', 'ss', 'ss', 'ss', '22'] lis_s = [word for word in lis if is_endwith_s(word)] print(lis_s) # ['ss', 'ss', 'ss', 'ss', 'ss', 'ss', 'ss'] ``` ```python def is_endwith_s(n): """ 判断是否以s结尾 :param n: str or int :return: bool """ return str(n).endswith('s') # 待判断的可迭代对象 lis = ['ss', 'ss', 'ss', 'aa', 'aa', 'ss', 'ss', 'ss', 'ss', '22'] lis_s = [word if is_endwith_s(word) else '666' for word in lis] print(lis_s) # ['ss', 'ss', 'ss', '666', '666', 'ss', 'ss', 'ss', 'ss', '666'] ``` # 附注 - [On writing Python one-liners.](http://blog.sigfpe.com/2008/09/on-writing-python-one-liners.html)