【问题标题】:How can I compare elements in same list and append to other list ? (Python)如何比较同一列表中的元素并附加到其他列表? (Python)
【发布时间】:2020-06-04 10:27:07
【问题描述】:

我想比较同一列表中的元素并附加到其他列表,但我遇到了一些问题。
例如:

a=[3,4,21,36,10,28,35,5,24,42]
c=[]

我想这样做:
4>3 追加到其他列表。
21>4 追加到其他列表。
36>21 追加到其他列表。
28>10 但不要'不要将此附加到其他列表,因为 36 大于 28。
结果应该是c=[4,21,36,42]

我试过这段代码:

b=0
d=1
while len(a)>b and len(a)>d:
    if a[d]>a[b]:
        c.append(a[d])

    b+=1
    d+=1

但它反而给了我: c=[4, 21, 36, 28, 35, 24, 42]

【问题讨论】:

  • 如果你只想追加比前一个元素大的元素,那么c=[4, 21, 36, 28, 35, 24, 42]是正确的答案...
  • 还需要比较a[d]和c[-1]来判断a的当前元素是否大于c的最后一个元素。

标签: python python-3.x list append compare


【解决方案1】:

试试这个:

a=[3,4,21,36,10,28,35,5,24,42]
c = []

for x in range(1,len(a)):
    count = 0
    for y in range(x):
        if a[x] > a[y]:
            count = count + 1
    if count == x:
        c.append(a[x])
print(c)

【讨论】:

  • 感谢您的帮助。它解决了我的问题,但我不明白情况。你为什么使用 if count == x: c.append(a[x]) ?
  • 如果 x 和 count 相同意味着 a[x] 之前的每个值都较低。
【解决方案2】:

你可以迭代和检查

currentList = [3,4,21,36,10,28,35,5,24,42]
newList = []
current_low = currentList[0]-1 # initialse current_low as [(first element of list) - 1]

for value in currentList:
    if value > current_low:
        newList.append(value)
        current_low = value

>>>print(newList)
[3, 4, 21, 36, 42]

【讨论】:

    【解决方案3】:

    花了一点时间才意识到您想要的数字小于之前的所有数字,而不仅仅是前面的数字。

    如果你想通过列表理解来做到这一点,你可以这样做:

    c = [a[i] for i in range(1,len(a)) if a[i] > max(a[:i])]
    

    结果:[4, 21, 36, 42]

    但是,如果您改变主意并决定想要比之前更大的数字,您可以这样做:

    c = [j for (i,j) in filter(lambda x: x[0] < x[1], zip(a, a[1:]))]
    

    结果:[4, 21, 36, 28, 35, 24, 42]

    【讨论】:

      猜你喜欢
      • 2017-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-18
      • 2017-12-23
      • 2020-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多