简体   繁体   English

在python中切片一个列表

[英]Slice a list in python

I have a list in python like:我在 python 中有一个列表,例如:

l = [1,2,4,5,7,8,2,1]

I want a code that will check if the number before in the list is bigger that the next one.我想要一个代码来检查列表中前面的数字是否大于下一个。 And if it is i want the code to remove the the number.如果是,我希望代码删除该号码。 I want my code to return [1,2,4,5,7,8] and remove the last 2 and 1 .我希望我的代码返回[1,2,4,5,7,8]并删除最后 2 和 1

Pseudo code:伪代码:

If l[i] > l[i+1]
remove l[i+1]
then check if l[i] is bigger than the next one after that. What use to be l[i+2]

Can someone help me?有人能帮我吗?

Started with your list and appended based upon your criteria to a new one.从您的列表开始,并根据您的标准附加到一个新列表中。

l = [1,2,4,5,7,8,2,1]

result = [] 
chk = 0 

for num in l:

  if chk > num:
    pass
  else:
    chk = num
    result.append(num)

print result

Apparently it is bad practice to delete entries from lists within a loop , so this is a workaround.显然,从循环内的列表中删除条目是不好的做法,因此这是一种解决方法。

Iterating through array if there is array[i] > array[i+1] then remove array[i+1].如果有数组[i] > 数组[i+1],则遍历数组,然后删除数组[i+1]。

array = [1,2,4,5,7,8,2,1]
l = len(array)

first = 0
secound = 1

while secound != l:
    if array[first] > array[secound]:
        del array[secound]
        l -= 1
    else:
        first += 1
        secound += 1

print(array)

You can use itertools groupby to find areas of lists that fulfill a condition;您可以使用itertools groupby来查找满足条件的列表区域; in this case, each number is larger than the number proceeding:在这种情况下,每个数字都大于进行的数字:

from itertools import groupby 

l = [1,2,4,5,7,8,2,1]

for k, g in groupby(enumerate(l[1:],1), key=lambda (i,e): e>l[i-1]):
    if k:
        grp=list(g)
        print l[grp[0][0]-1:grp[-1][0]+1]
        # [1, 2, 4, 5, 7, 8]

This will find any area in the list that meets that condition:这将在列表中找到满足该条件的任何区域:

l = [1,2,4,5,7,8,2,5]

for k, g in groupby(enumerate(l[1:],1), key=lambda (i,e): e>l[i-1]):
    if k:
        grp=list(g)
        print l[grp[0][0]-1:grp[-1][0]+1]
        # prints [1, 2, 4, 5, 7, 8] and [2, 5]

So break after the first if you only want 1 group:因此,如果您只想要 1 组,请在第一个之后休息:

l = [10, 11, 12, 1, 2]
for k, g in groupby(enumerate(l[1:],1), key=lambda (i,e): e>l[i-1]):
    if k:
        grp=list(g)
        print l[grp[0][0]-1:grp[-1][0]+1]
        break
        # [10, 11, 12]

you can do this even in one line:您甚至可以在一行中执行此操作:

     l = l[0:1] + [el for index,el in enumerate(l[0:])  if el >l[index-1]]
     #l[0:1] + is ugly but i couldnt figure out another way to get the
     #first element since in python l[-1] = l[len(l)-1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM