3月14号:instruction:In this kata you will create a function that takes a list of non-negative integers and strings and returns a new list with the strings filtered out.
给你个列表,表里有非负数和字母,要求剔除字母保留非负整数。
def filter_list(l):
new_l =[] #新建一个数组
for x in l: #遍历一个数组里每一个元素
if type(x) != str: #判断每一个元素的数据类型,type()函数
new_l.append(x) #添加进新数组
return new_l
写了几次都不成功,以上答案是可以的,思路是可行的。
type()函数判断数据类型,append()向数组里添加元素,for x in l:遍历数组中每一个元素。
同样的isinstance ()函数同样也可以判断数据类型。remove()和del()都有去除数组元素的功能。
最简单的答案:
def filter_list(l):
'return a new list with the strings filtered out'
return [i for i in l if not isinstance(i, str)]
充分利用了python语言的简约性。
3月15号:In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative?
给你一个数,如果是负数保持原样,如果是正数,将其变为负数输出。
def make_negative(number):
if number >= 0:
number = 0 - number
return number
我自己写出,没有问题。但还可以再简化一下:
def make_negative(number):
if number >= 0:
return 0 - number
3月19号:
Make a program that filters a list of strings and returns a list with only your friends name in it.
If a name has exactly 4 letters in it, you can be sure that it has to be a friend of yours! Otherwise, you can be sure he's not...
给你一个数组,里面有各种名字,返回一个数组里面只有4个字符的才能保留其中
自己写出:
def friend(x):
Name = []
for name in x:
if len(name) == 4:
Name.append(name)
return Name
别人更简单的方法:
def friend(x):
return list(filter(lambda s : len(s)==4 ,x))
filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换。
该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。
3月21号:
题意:在给你的列表中找出needle,返回的索引。
没有做出来,别人的答案
def find_needle(haystack):
for i, x in enumerate(haystack):
if x == 'needle':
return 'found the needle at position %d' % i
enumerate函数用于遍历序列中的元素以及它们的下标