# 进阶题目
# 先做后看答案
# 1:给定列表和目标值,从列表找到与目标值匹配的对象并输出
strings = [
[
"hello there",
"how are you",
],
[
"goodbye world",
"hello world",
]
]
word = "hello"
hello there
hello world
# 2:给定列表和目标值,从子列表中找到包含目标值的子列表,若子列表包含则输出True,反之输出False
strings = [
[
"hello there",
"how are you",
],
[
"goodbye world",
"hello world",
]
]
word = "goodbye"
False
True
# 3:给定列表和目标值,判断该列表是否包含目标值,包含则输出True,反之输出False
strings = [
[
"hello there",
"how are you",
],
[
"goodbye world",
"hello world",
]
]
word = "Python"
False
# 4:给定列表,将列表中每个字符串的首字母,拼接起来成新字符串并输出,长度不够的使用空格代替(你的代码要通过以下三个列表的测试,每段列表的下面对应是正确输出)
-- 4.1 strings = ["abc", "def", "ghi"]
adg
beh
cfi
-- 4.2 strings = [" b n", "f ete", "liths", "astat", "t ene", " r d"]
flat
is
better
than
nested
-- 4.3 strings = ["abcqwe", "def", "ghiq"]
adg
beh
cfi
q q
w
e
--1
for string in strings:
for words in string:
if word in words:
print(words)
--2
for string in strings:
present = False
for words in string:
if word in words:
present = True
print(present)
--3
present = False
for string in strings:
for words in string:
if word in words:
present = True
print(present)
--4
lengths = []
for string in strings:
lengths.append(len(string))
length = max(lengths)
for i in range(length):
line = ''
for string in strings:
if i >= len(string):
line += ' '
else:
line += string[i]
print(line)
# 心得体会 #
题目难度由简单到复杂,不变的思路和方法,Break Down (分解问题),我习惯先写出最主要的一行的代码,然后补充上文,运用基础知识(温故而知新),从点到线再到面,一点点的整个代码就出来了(实在写不出来就利用浏览器吧),但是一定要找出自己出错的地方在哪儿?(某个知识点忘记了?某个逻辑没转过弯?某个知识点运用错误了?某个基础语法忘记?等),然后一步步分析自己的代码和正确代码,再重新做一遍,效果很好!
# 案例分析 #
就拿第四题来说,找到问题关键--最合适的遍历次数(也就是找到列表中最长的字符串,并转换成整数),所以这里利用循环遍历列表,将每个字符串(对象)的长度加到空列表中,再利用max方法找出最大的数(最长的字符串的长度),到这里基本就成功一半。接下来分解问题,找到核心,该问题的核心是什么时候该添加空格,这里需要判断列表中字符串的长度与循环次数的大小,若次数大于并且等于字符串长度,则添加空格,到这里就离成功只差一步。最后确定外层循环和内存循环分别的循环次数(利用假设方法),假设你要把最长的字符串里的每个字符打印出来,肯定不能最长的循环次数放到内存,这样会导致外层超出遍历范围,所以自然外层循环次数是最长的字符串长度。(这是我个人理解,有更好的解题思路,欢迎评论)