如果满足条件,如何截断列表

时间:2019-05-28 09:24:32

标签: python list

我有一个值列表,基本上我想浏览一下该列表,并检查是否有20个以上的连续值低于某个最小值。如果是这样,我要结束列表中最后一个高于最小值的数字。

我尝试了以下失败的尝试:

def build_profile(first, last, **user_info):
         """Build a dictionary containing everything we know about a user."""
   profile = {}
   profile['first_name'] = first
   profile['last_name'] = last
   for key, value in user_info.items():
      profile[key] = value
   return profile
user_profile = build_profile('albert', 'einstein',
                  location='princeton',
                   field='physics')
print(user_profile)

2 个答案:

答案 0 :(得分:1)

您应该这样子- (将此视为伪代码)

your_list = [.....]
counter = 0
stop_at = 20  #Set it accordingly
minimum = 30  # Set it accordingly
split_at_index = None
for index, list_item in enumerate(your_list):
    if list_item < minimum:
        counter += 1
    else:
        counter = 0
        continue
    if counter == stop_at:
        split_at_index = index
        break
new_list = your_list[:split_at_index]

答案 1 :(得分:0)

_list = [12,34,41,145,11,43,123,32]
counter = 0
limit = 3
thresold = 50
index = 0
split = 0
for num in _list:
    if num < thresold:
        counter = counter + 1
        print counter
        if counter == limit:
            split = index
            break
    else:
        counter = 0
    index = index + 1

print (_list[:split])