将相似元素从一个列表移动到另一个列表
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 的新手并感到困惑。我也意识到我现在没有 else 声明。
您正在迭代 set
。
集合对象不允许有多个项目,因此如果您有列表 [4,5,6,4,5,3,4,5,4]
,结果集合将为 [3,4,5,6]
。
然后您将迭代 [3,4,5,6]
,这就是为什么它只会进入 if
语句一次:仅当 i == 4
.
我不知道你打算在那里做什么,但如果你想将 human_hand
中的所有四个元素附加到 discard
,一个更简单的方法是不迭代集合:
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)
时,您正在迭代一个集合,因此每个数字只表示一次。如果您想在每次 4 出现在原件中时追加,只需遍历 for i in human_hand
简而言之,我试图检测列表中是否有 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 的新手并感到困惑。我也意识到我现在没有 else 声明。
您正在迭代 set
。
集合对象不允许有多个项目,因此如果您有列表 [4,5,6,4,5,3,4,5,4]
,结果集合将为 [3,4,5,6]
。
然后您将迭代 [3,4,5,6]
,这就是为什么它只会进入 if
语句一次:仅当 i == 4
.
我不知道你打算在那里做什么,但如果你想将 human_hand
中的所有四个元素附加到 discard
,一个更简单的方法是不迭代集合:
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)
时,您正在迭代一个集合,因此每个数字只表示一次。如果您想在每次 4 出现在原件中时追加,只需遍历 for i in human_hand