[英]Moving similar elements from one list to another
簡而言之,我試圖檢測列表中是否存在一種元素中的4種,然后將所有這4種元素移動到另一個列表中。 到目前為止,我有:
human_hand = [4,5,6,4,5,3,4,5,4]
discard = []
for i in set(human_hand):
if human_hand.count(i) == 4:
discard.append(i)
print discard
但是,我的問題是,一旦第一個附加了布爾值,就不再觸發布爾值。 是python的新手,很困惑。 我也意識到我現在沒有其他聲明。
您正在遍歷一set
。
Set對象不允許有多個項目,因此,如果您有列表[4,5,6,4,5,3,4,5,4]
,則結果集將為[3,4,5,6]
。 然后,您遍歷[3,4,5,6]
,因此這就是為什么它僅進入if
語句一次的原因:僅當i == 4
。
我不知道您打算在那里做什么,但是如果您希望將human_hand
所有四個元素附加到discard
, human_hand
簡單的方法是不遍歷集合:
for i in human_hand:
if human_hand.count(i) == 4:
discard.append(i)
如果您想追加4次以做discard
列表,但是如果沒有4個用戶,則僅通知一次用戶,則可以使用:
for i in set(human_hand):
if human_hand.count(i) == 4:
discard.extend([i]*4)
else:
print "There aren't 4 of a kind for the number ", i
這將附加到丟棄列表[4,4,4,4]
但如果沒有其他4個項目,則僅注意一次。
for i in set(human_hand)
調用for i in set(human_hand)
您正在遍歷一個set,因此每個數字僅表示一次。 如果您想每次在原始文件中出現4時追加,只需for i in human_hand
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.