简而言之,我试图检测列表中是否有一种元素,然后将所有这四个元素移动到另一个列表中。到目前为止,我有:
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和难倒。我也意识到我现在没有其他声明。
答案 0 :(得分:0)
您正在迭代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项,则只会注意一次。
答案 1 :(得分:0)
当调用for i in set(human_hand)
时,你正在迭代一组,所以每个数字只代表一次。如果您想在每次4出现在原文中时附加,只需迭代for i in human_hand