簡體   English   中英

如何更改 python 列表中特定數量的項目

[英]how to change a specifc number of items in a list in python

我有一個這樣的列表:

 my_list=[False, False, True, True, False, False, True]

我想更改此列表,以便第 n 個出現的 True 保持原位,而所有其他的都變為 False。

例如,如果 n=1,我想創建一個與此相同的新列表:

my_new_list=[False, False, True, False, False, False, False]

如果n=2; 應創建此列表:

my_new_list=[False, False, True, True, False, False, False]

我可以輕松地在 for 循環中執行此操作,但是在 Python 中執行此操作的最佳方法是什么?

編輯1

這是我的代碼:

def f(l,n):
   c=1
   new_l=[False] * len(l)
   if n>= len(l):
       return new_l
   for i,v in enumerate(l):
      if v:
         if(c >= n):
            return new_l
         new_l[i]=True
         c +=1
        
   return new_l

此代碼遍歷列表中的所有項目,但只是其中的一部分。 但是它有 9 行代碼,有沒有更短的版本或更快的版本?

使用列表組合:

my_new_list = [x and (n := n - 1) >= 0 for x in my_list]

在線嘗試!

您可以使用累積(來自 itertools)來計算到目前為止您有多少 True 值並將其與n的值匹配:

my_list=[False, False, True, True, False, False, True]

from itertools import accumulate

n = 1
r = [isTrue and count<=n for isTrue,count in zip(my_list,accumulate(my_list))]
print(r)
[False, False, True, False, False, False, False]

n = 2
r = [isTrue and count<=n for isTrue,count in zip(my_list,accumulate(my_list))]
print(r)
[False, False, True, True, False, False, False]

使用 numpy

同樣的方法可以更簡潔地用於 numpy:

import numpy as np

my_list=[False, False, True, True, False, False, True]

n=1
r = my_list & (np.cumsum(my_list)<=n)
print(r)
# [False False  True False False False False]

n=2
r = my_list & (np.cumsum(my_list)<=n)
print(r)
# [False False  True  True False False False]
def function(l,n):
new_list = []
c = 0
for i in l:
    if not i:
        new_list.append(False)
    else:
        if c < n:
            new_list.append(False)
            c+=1
        else:
            new_list.append(True)
return new_list

或者:

def function(l,n):
return [False if (not i) or (n := n-1) >= 0 else True for i in l]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM