我希望此代碼為串列 p 中第一次出現在串列 s 中的專案附加 1,并為其他出現和 s 中的其他專案附加 0。
這是我下面的當前代碼,它為所有出現附加 1,我希望它僅在第一次出現時附加 1。請幫忙
s = [20, 39, 0, 87, 13, 0, 23, 56, 12, 13]
p = [0, 13]
bin = []
for i in s:
if i in p:
bin.append(1)
else:
bin.append(0)
print(bin)
# current result [0, 0, 1, 0, 1, 1, 0, 0, 0, 1]
# excepted result [0, 0, 1, 0, 1, 0, 0, 0, 0, 0]
uj5u.com熱心網友回復:
最簡單的解決方案是從串列中洗掉該專案(p如果找到):
s = [20, 39, 0, 87, 13, 0, 23, 56, 12, 13]
p = [0, 13]
out = []
for i in s:
if i in p:
out.append(1)
p.remove(i)
else:
out.append(0)
print(out)
印刷:
[0, 0, 1, 0, 1, 0, 0, 0, 0, 0]
uj5u.com熱心網友回復:
用于index查找串列中的第一個匹配項。
s = [20, 39, 0, 87, 13, 0, 23, 56, 12, 13]
p = [0, 13]
bin = [0] * len(s)
for value in p:
bin[s.index(value)] = 1
uj5u.com熱心網友回復:
您必須記住您是否曾經看過該元素。為此使用一套。
s = [20, 39, 0, 87, 13, 0, 23, 56, 12, 13]
p = [0, 13]
bin = []
seen = set()
for i in s:
if i in p:
if i in seen:
bin.append(0)
else:
bin.append(1)
seen.add(i)
else:
bin.append(0)
print(bin)
結果是[0, 0, 1, 0, 1, 0, 0, 0, 0, 0]
這僅在資料上運行一次,并且不會修改任何輸入值。
回圈的壓縮版本:
for i in s:
if i in p and i not in seen:
bin.append(1)
seen.add(i)
else:
bin.append(0)
uj5u.com熱心網友回復:
正如一些人正確指出的那樣,一些解決方案會發生變化s,p因此重新運行是不一致的。所以要小心。
我會用一個很好的方法來包裝它:
import copy
def mark_first_key_occurence(values, keys):
def account_for(v, c):
if v not in c:
return 0
c.remove(v)
return 1
keys_copy = copy.deepcopy(keys)
return [account_for(v, keys_copy) for v in values]
然后使用以下命令呼叫它:
s = [20, 39, 0, 87, 13, 0, 23, 56, 12, 13]
p = [0, 13]
print(mark_first_key_occurence(s, p))
更新:凱利的解決方案毫無疑問是最好的。串列沒有pop默認的 -like 方法,但使用 dict 絕對是一個巧妙的技巧!請給他功勞。
這是我的輕微接觸(我認為pop顯式呼叫更清潔)
d = dict.fromkeys(p, 1)
print([d.pop(i, 0) for i in s])
uj5u.com熱心網友回復:
O(|s| |p|) 時間并且不修改輸入:(在線嘗試!):
d = dict.fromkeys(p, 1).pop
bin = [d(i, 0) for i in s]
uj5u.com熱心網友回復:
s = [20, 39, 0, 87, 13, 0, 23, 56, 12, 13]
p = [0, 13]
bin = [0]*len(s) # let the array contain only 0
for i in p: # for each element in p
flag = False # this flag is made to true if the first occurence has been set to 1 in the bin array
for j in range(len(s)):
if((s[j]==i) and (not flag)):
bin[j] = 1
flag = True
print(bin)
uj5u.com熱心網友回復:
更優雅的方式:
s = [20, 39, 0, 87, 13, 0, 23, 56, 12, 13]
p = [0, 13]
bin = [1 if x in p else 0 for x in s]
idxs = [idx for idx, item in enumerate(s) if item in s[:idx]]
for idx in idxs:
bin [idx] = 0
print(bin)
[0, 0, 1, 0, 1, 0, 0, 0, 0, 0]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/482188.html
標籤:Python python-3.x 列表 python-2.7 循环
上一篇:陣列中所有物件的1個物件的值變化
下一篇:獲取嵌套陣列JS中物件的所有父項
