Discuss / Python / 交作业

交作业

Topic source

IM_Dull

#1 Created at ... [Delete] [Delete and Lock User]

1.练习要求:

L2 = [s.lower() for s in L1 if isinstance(s,str)]

2.若满足将大写字母改变为小写字母且同时不删减原List的内容:

L2 = [s.lower() if isinstance(s,str) else s for s in L]

请问第二项里的条件怎么理解?当if的条件成立时,else里的循环也进行吗?

join87

#2 Created at ... [Delete] [Delete and Lock User]
# 1.保持元素个数不变:if-else判断放在for的前面时,遍历结果会输出所有的元素,只是对每个元素通过if-else做不同的处理(并不会过滤掉某些元素)
print([(s.lower() if isinstance(s,str) else s) for s in L])  

# 2.过滤掉非字符的元素:if判断放在for的后面,表示只输出满足if的元素,遍历结果会过滤掉某些元素
print([s.lower() for s in L if isinstance(s,str)])

晨小伍

#3 Created at ... [Delete] [Delete and Lock User]

第二项不能理解,其实是理解的时候断句没断好 这么断句,就可以理解了: [s.lower() if isinstance(s,str) else s for s in L]

s.lower() if isinstance(s,str) else s 这是一句,对s的处理 for s in L这是另一句,迭代


  • 1

Reply