【问题标题】:Move specific items to end of a list Python [duplicate]将特定项目移动到列表Python的末尾[重复]
【发布时间】:2020-06-09 20:13:25
【问题描述】:

我有一个列表,我想将带有 '1' 的元素移到列表末尾。

例如,我有一个列表: 测试 = [['dogs',2], ['cats', 3], ['dogs',4] , ['dogs', 1], ['cats', 11], ['cats',1] , ['鸟',1], ['鸟', 12]]

我想将所有以“1”作为第二个元素的列表移动到列表“Test”的末尾。到目前为止,

def score_hand(hand):

#Setting the appropriate values for the cards and moving the ones to the back

for card in hand:
    if hand[hand.index(card)][1] == 1:
        hand.append(card)
        hand.remove(card)

但是,执行此操作时,我的循环会跳过一个元素。我是一个新的编码员,我不确定该怎么做。

【问题讨论】:

    标签: python python-3.x list loops methods


    【解决方案1】:

    我不确定 python 中的实现细节,但是在大多数语言中,在迭代列表时修改列表是危险的;简而言之,跟踪您在列表中的位置的东西可能会混淆。

    一种可能的解决方案是存储以 1 结尾的元素列表,然后在第二个循环中执行所有删除/附加操作。

    【讨论】:

      猜你喜欢
      • 2014-05-19
      • 2020-04-07
      • 2016-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-15
      • 2017-07-10
      相关资源
      最近更新 更多