我有一个这样的清单:
List1: [1, 5, 9, 1, 5, 9, 15, 21, 29, 1, 5, 9, 15]
我想要一个新的列表,它应该包含最高的数字,然后再用1开始。
List_new: [9, 29, 15]
我试过了:
List_new = []
for i in range(len(List1)):
j = List1[i]
if j + 1 == '1':
List_new += [j]
else:
continue
print(j)
但我得到了一个空列表。
答案 0 :(得分:11)
只需内置libs:
from itertools import groupby
result = [max(group) for r, group in groupby(your_list, lambda x: x == 1) if not r]
答案 1 :(得分:2)
def max_of_sublists(megalist):
maxitem = 0
for item in megalist:
if item == 1 and maxitem:
yield maxitem
maxitem = 0
if maxitem < item:
maxitem = item
yield maxitem
biglist=[1, 5, 9, 1, 5, 9, 15, 21, 29, 1, 5, 9, 15]
print([x for x in max_of_sublists(biglist)])
答案 2 :(得分:2)
您的代码存在一些问题。这是一个有效的版本。
list1 = [1, 5, 9, 1, 5, 9, 15, 21, 29, 1, 5, 9, 15]
list2 = []
for i in range(len(list1)-1):
if list1[i+1] == 1:
list2.append(list1[i])
list2.append(list1[-1]) # adds the last element
输出:
>>> list2
[9, 29, 15]
答案 3 :(得分:1)
这是一个简单的for
循环,可以回答您的问题:
List_new = [List1[0]] # initialize with first element
for i in List1[1:]: # simply iterate over list elements, not indices
if i != 1 and i > List_new[-1]:
List_new[-1] = i # current element is the new maximum
elif i == 1:
List_new.append(i) # encountered a 1, start looking for new maximum
请参阅内联注释以获取解释。
答案 4 :(得分:1)
这个问题可以使用python模块在一个内核中实现,就像Andrey建议的非常优雅的解决方案一样。但是,如果您想要遵循逻辑,请查看此解决方案。
def max_values_between_ones(numbers):
max_values = []
max_value = None
for i in range(len(numbers)):
if numbers[i] == 1:
if max_value != None:
max_values.append(max_value)
max_value = None
# max_value is None when they were no values != 1 before this 1
else:
if max_value != None:
# this part was missing in your code, to get the max value
# you should be comparing the current value with the max value so far
max_value = max(numbers[i], max_value)
else:
# set max_value to any not 1 value
max_value = numbers[i]
# if the list didn't end with 1, add the last max_value
if max_value != None:
max_values.append(max_value)
return max_values
numbers = [1, 5, 9, 1, 5, 9, 15, 21, 29, 1, 5, 9, 15]
max_values = max_values_between_ones(numbers)
print(max_values)
>> [9, 29, 15]
答案 5 :(得分:0)
像这样:
l = [1, 5, 9, 1, 5, 9, 15, 21, 29, 1, 5, 9, 15]
pos = [item for item in range(0, len(l)) if l[item] == 1]
new_list = []
for n in range(len(pos)):
if n != len(pos) - 1:
new_list.append(l[pos[n]:pos[n+1]])
else:
new_list.append(l[pos[n]:])
print map(lambda x: max(x), new_list)
答案 6 :(得分:0)
List1 = [1, 5, 9, 1, 5, 9, 15, 21, 29, 1, 5, 9, 15]
maxi = 0
List2 = []
for i in range(0,len(List1)):
if maxi < List1[i]:
maxi = List1[i]
if (i == len(List1)-1 or List1[i] == 1) and maxi > 1:
List2.append(maxi)
maxi = 0
print List2