我的代码遇到问题,我正在编写一个方法来检查下一个元素是否小于前一个元素,如果是,则删除它。
示例:
输入:[1, 20, 10, 30]
所需的输出:[1,20,30]
实际输出:[30]
def findSmaller(s):
i = -1
y = []
while i <= len(s):
for j in range(len(s)):
if s[i+1] <= s[i]:
del s[i + 1]
y.append(s[i])
i += 1
return y
答案 0 :(得分:1)
根据您是否需要稍后使用列表进行计算,您可以使用生成器
s = [1, 20, 10, 30]
def find_smaller_generator(l: list):
last_item = None
for item in l:
if last_item is None or item >= last_item:
last_item = item
yield item
def find_smaller_list(l: list):
return list(find_smaller_generator(l))
print(find_smaller_list(s))
for i in find_smaller_generator(s):
print(i)
print([i**2 for i in find_smaller_generator(s)])
返回:
[1, 20, 30]
1
20
30
[1, 400, 900]
答案 1 :(得分:1)
>>> s = [5, 20, 10, 15, 30]
>>> max_so_far = s[0]
>>> result = []
>>> for x in s:
if x >= max_so_far:
result.append(x)
max_so_far = x
>>> result
[5, 20, 30]
答案 2 :(得分:0)
您可以尝试这样的事情
def findSmaller(s):
# sets p (previous) as the first value in s
p = s[0]
# initializes y to be an array and sets the first value to p
y = [p]
# iterates over s, starting with the second element
for i in s[1::]:
# checks if i is greater than or equal to the previous element
if i >= p:
# if it is, i is appended to the list y
y.append(i)
# also set the previous value to i, so the next iteration can check against p
p = i
#returns the list
return y
这样做是迭代s
并检查列表中的当前项是否大于或等于列表中的前一个元素。如果是,则将其附加到y
,并返回y
。
试用代码here。
答案 3 :(得分:0)
如果您不确定循环如何工作我建议添加一些打印语句。这样你就可以看到你的循环实际上在做什么,特别是在更复杂的问题中这是有用的。
这样的事情可以解决你的问题。
a = [1,2,3,2,4]
for k in range(0,len(a)-2): #-2 so that one don't go past the loops length
#print(k)
y = a
if(a[k]>a[k+1]):
del y[k+1] #delete the k+1 element if it is