SRE/level0(T).py
2025-05-19 20:04:46 +08:00

21 lines
1.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#题目:怎么用推导式将下面这个列表中的元素遍历出来,只留下字母数字空格和花括号,并输出一个完整的字符串呢?
# [["RE", "DR✍O", "CK{❦"], ["I a", "m le♫a", "rn†‡in"], ["g Py✣✤✥t", "ho⇒⇓⇔⇕na", "t SR々E}"]]
#思路先使用循环遍历出子列表、字符串、字符使用isspace()、isalnum()判断是否为空格、数字或字符最后输出result。注意遍历每个字符过滤而非字符串
# 一步完成:展平嵌套结构 + 过滤特殊字符 + 拼接字符串
lst = [["RE", "DR✍O", "CK{"], ["I a", "m le♫a", "rn†‡in"], ["g Py✣✤✥t", "ho⇒⇓⇔⇕na", "t SR々E}"]]
#join()是一个字符串方法,用于将可迭代对象中的元素连接为一个字符串
#' '.join() 以空格来连接
result = ''.join(
char for sublist in lst #生成器表达方式,遍历外层列表,char是接收最后用于输出的字符
for s in sublist # 遍历每个子列表中的字符串
for char in s # 遍历字符串的每个字符
if char.isalnum() or char.isspace() or char in '{}'
)
print(result)