![](/img/trans.png)
[英]Output of my python list / array is repeating the values. How do I remove this?
[英]How do I remove these values in a list in Python?
x1 = [1, 2, 3, 4, 5, 6]
x2 = [3, 5, 6, 8, 9]
x3 = [2, 4, 5, 7, 13]
x4 = [11, 22, 33, 24, 55, 66]
x5 = [11, 7, 1, 2, 3, 4, 5, 6]
如何刪除每個列表上的遞增值?
如果我刪除了那些列表中的增加項,則它們應如下所示:
x1 = [1, 6]
x2 = [3, 9]
x3 = [2, 13]
x4 = [11, 33, 24, 66]
x5 = [11, 7, 1, 6]
您可以使用生成器來構建運行並yield
結果,例如:
def runs(iterable):
iterable = iter(iterable)
i = [next(iterable)] # Empty iterable not handled
for j in iterable:
while j and i[-1] < j:
i.append(j)
j = next(iterable, None)
i[1:-1] = [] # Removes the middle of the run, if there is one
yield from i
i = [j]
if j:
yield j
# Using @StephenRauch data set
data = (
[1, 2, 3, 4, 5, 6],
[3, 5, 6, 8, 9],
[2, 4, 5, 7, 13],
[11, 22, 33, 24, 55, 66],
[11, 7, 1, 2, 3, 4, 5, 6]
)
>>> [list(runs(d)) for d in data]
[[1, 6], [3, 9], [2, 13], [11, 33, 24, 66], [11, 7, 1, 6]]
這將刪除所有增加的元素:
def remove_increasing(a_list):
return [a_list[0]] + \
[y for x, y in zip(a_list, a_list[1:]) if x >= y] + \
[a_list[-1]]
data = (
[1, 2, 3, 4, 5, 6],
[3, 5, 6, 8, 9],
[2, 4, 5, 7, 13],
[11, 22, 33, 24, 55, 66],
[11, 7, 1, 2, 3, 4, 5, 6]
)
for d in data:
print(remove_increasing(d))
[1, 6]
[3, 9]
[2, 13]
[11, 24, 66]
[11, 7, 1, 6]
您的問題不清楚。 “刪除增加的值”是什么意思?
顯然,您的意思不是說“刪除每個大於上一個值的值”,因為示例結果包括最后一個較大的元素。
但是,假設你知道你的意思,這里是如何做到這一點:
要從列表中刪除值:
mylist.remove(4)
要從列表中的特定位置刪除項目:(請記住,Python列表從位置0開始,而不是位置1開始)
del mylist[2]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.