我有這個值串列:
A = [0,0,1,2,3,4,5,6,0,6,6,8,8,0,0,2,3,4,5,12,45,-0,-0,-9,-2,3,-0,-2,-2,-2]
我想得到這個輸出值串列:
A = [1,2,3,4,5,6,0,6,6,8,8,2,3,4,5,12,45,-9,-2,3,-0,-2,-2,-2]
基本上,我只想洗掉連續的零,并保留所有其他值。
你知道我該怎么做嗎?我試過這個,但我知道會有索引錯誤:
X = []
for j in range(len(A)):
if A[j] != 0 and A[j 1] != 0:
X.append(A[j])
else:
print('lol')
print(X)```
uj5u.com熱心網友回復:
您可以使用itertools.groupby和itertools.chain:
from itertools import groupby, chain
out = list(chain.from_iterable(G for k,g in groupby(A)
if len(G:=list(g))<2 or k!=0))
解釋:
groupby將對連續值進行分組。對于每一組,如果長度不超過1或者key(=value)不為0,則保留。最后chain將所有組放在一起并轉換為串列。
請注意,它groupby回傳迭代器,因此我使用賦值運算式來執行轉換。
輸出:
[1, 2, 3, 4, 5, 6, 0, 6, 6, 8, 8, 2, 3, 4, 5, 12, 45, -9, -2, 3, 0, -2, -2, -2]
uj5u.com熱心網友回復:
與itertools:
from itertools import groupby
X = [x
for x, [*xs] in groupby(A)
if x or len(xs) == 1
for x in xs]
或者:
X = []
for x, [*xs] in groupby(A):
if x or len(xs) == 1:
X = xs
或者取任何x不為零的值或前一個值和下一個值不為零的值(用 填充1):
X = [x
for p, x, n in zip([1] A, A, A[1:] [1])
if x or p and n]
uj5u.com熱心網友回復:
如果您不想匯入 itertools 而更喜歡串列理解
A = [i for index,i in enumerate(A) if i!=0 or index not in [0,len(A)] and A[index-1]!=i and A[index 1]!=i ]
請注意,此運算式使用and 運算子優先于 or 運算子
enumerate也被使用
uj5u.com熱心網友回復:
這里有一個更簡單易行的方法來解決你的問題
A = [0,0,1,2,3,4,5,6,0,6,6,8,8,0,0,2,3,4,5,12,45,-0,-0,-9,-2,3,-0,-2,-2,-2]
A=[f"'{str(int)}'" for int in A]
a=",".join(A).replace("'0'","").replace("'","").split(",")
b=[i for i in a if i != ""]
c=[int(i) for i in b]
d_output=[1,2,3,4,5,6,0,6,6,8,8,2,3,4,5,12,45,-9,-2,3,-0,-2,-2,-2]
if c==d_output:
print(1)
輸出:1 即您想要的輸出
如果要指定值,則可以將其包裝在一個函式中,如下所示:
def remove_con(l,val):
A=[f"'{str(int)}'" for int in l]
a=",".join(A).replace(f"'{val}'","").replace("'","").split(",")
b=[i for i in a if i != ""]
c=[int(i) for i in b]
return c
print(remove_con(A,0))
- 首先,我將串列中的整數轉換為字串。
- 然后用方法加入它們
.join,用“”用方法代替“'0'”.replace,然后用“,”用方法代替串列.split。 - 然后洗掉空元素,即“”元素。
- 然后再次將字串轉換為整數。
我注意到您的代碼中有一個愚蠢的錯誤:
X = []
for j in range(len(A)): # Mistake here
if A[j] != 0 and A[j 1] != 0: # if we bypassed the above error we can also get error here
X.append(A[j])
else:
print('lol')
print(X)
問題是當 i 是串列的最后一個索引時,將沒有其他索引,但您已硬編碼以搜索 index 1,因此會引發錯誤。
有兩種方法可以解決這個問題:
- 使用
try和except。 - 替換
range(len(A)為range(len(A)-1)。
有用的參考資料:
.split.replace.join
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/435217.html
