def f(p):
z=len(p)
for y in range(0,z):
if "t" in p[y]:
print(p[y])
return
list = ["titan","ton", "automatic","manual"]
f(list)
函数应该删除从列表中以字母't'开头的所有单词。该函数然后返回该列表。这个函数只是返回一个列表,其中包含t的所有单词。For循环列表函数
def f(p):
z=len(p)
for y in range(0,z):
if "t" in p[y]:
print(p[y])
return
list = ["titan","ton", "automatic","manual"]
f(list)
函数应该删除从列表中以字母't'开头的所有单词。该函数然后返回该列表。这个函数只是返回一个列表,其中包含t的所有单词。For循环列表函数
根本没有返回列表,只是打印它的项目。
其次,不需要使用索引来遍历列表项,只需遍历列表本身即可。使用
解决一个list comprehension:
def f(p):
return [item for item in p if item.startswith('t')]
lis = ["titan","ton", "automatic","manual"]
new_lis = f(lis)
print(new_lis)
#['titan', 'ton']
您可以通过简单地用yield
更换print
呼叫并做了一些其他改变使你的代码工作。使用yield
使得这个功能generator function:
def f(p):
for item in p:
if item.startswith('t'):
yield item
...
>>> list(f(lis)) #call list on the generator expression returned by `f` to see its content
['titan', 'ton']
注意in
运算符用于字符串匹配,所以:
>>> "t" in "automatic"
True
是True
,如果你要检查只是第一个字符,然后使用str.startswith
:
>>> "automatic".startswith('t')
False
你的问题是双重的:
但是,您不需要为这项工作很大的功能。只需使用一个list comprehension过滤掉这些项目:
>>> lst = ["titan","ton", "automatic","manual"]
>>> def func(lst):
... # You could also do `[x for x in lst if not x.lower().startswith("t")]`
... # which will also capture words starting with "T"
... return [x for x in lst if not x.startswith("t")]
...
>>> # Reassign 'lst' to the cleaned list
>>> lst = func(lst)
>>> lst
['automatic', 'manual']
>>>
你的函数返回None
,但它打印出所有与他们"t"
的话。你想要的是像
def f(p):
no_ts = []
for el in p:
if not el.startswith("t"):
no_ts.append(el)
return no_ts
它可以方便地与列表理解
[el for el in p if not el.lower().startswith("t")]
# .lower() makes sure to catch words that start with "T"
也做,这是最好的,如果你不跟喜欢“清单保留名称命名变量混淆了命名空间“或”str“。
您可以使用过滤器:
>>> li=["titan","ton", "automatic","manual"]
>>> filter(lambda s: not s.startswith('t'), li)
['automatic', 'manual']
它不返回任何东西。 – kindall
不要使用'list'作为变量名! – dawg