ループ内のために使用した場合、リストの先頭に項目を移動します

cclloyd:

何が反復してリストを、リストの先頭に項目を移動するための最も神託の方法だろうfor inループ?

など:

for item in items:
    if condition:
        # Move `item` to front of `items`
        break
Sayandip Dutta氏:

それを反復しながら、一般的に推奨されていない、リストを変更する、それは言いました:

>>> ctr = 0
>>> lst = [1,2,3,4,5,6]
>>> for i in lst:
...:     if ctr == 3:
...:         lst.insert(0,lst.pop(ctr))
...:         break
...:     ctr += 1
...:
>>> lst
[4, 1, 2, 3, 5, 6]

または、

>>> lst = [1,2,3,4,5,6]
>>> for i,x in enumerate(lst):
...     if x == 3:
...         lst.insert(0,lst.pop(i))
...         break
>>> lst
[3, 1, 2, 4, 5, 6]

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=16782&siteId=1